jdbcMySQL_0">jdbc原生代码访问MySQL数据库>jdbc原生代码访问MySQL数据库
1、引入MySQL连接JAR包
2.新建.Java文件,编写数据库连接代码
public class JdbcConnectorMysql {
public static void main(String arg[]) {
Connection con = null;
PreparedStatement stmt=null;
ResultSet resultSet=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
String sql="SELECT * FROM `user_info` WHERE `user_name`=?";
stmt = con.prepareStatement(sql);
stmt.setString(1,"admin");
resultSet= stmt.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getString("user_id")+"..............."+resultSet.getString("user_name"));
}
} catch (Exception e) {
System.out.print("MYSQL ERROR:" + e.getMessage());
}finally {
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
3.运行结果