下载jar包:

mysql-connector-java-5.1.44.jar

导入包:

import java.sql.*;

源码如下:

    /**
* 使用JDBC底层实现查询
*/
public static void queryWithJDBC() {
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
String jdbcUrl = "jdbc:mysql://192.168.184.130:3306/gxrdb"; try {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 创建连接
conn = DriverManager.getConnection(jdbcUrl, "root", "root");
String sql = "select * from user where name = ?";
// 预编译sql
psmt = conn.prepareStatement(sql);
// 从1开始,没有就不需要
psmt.setString(1, "Tom");
// 执行sql
rs = psmt.executeQuery();
// int num = psmt.executeUpdate(); //增删改,返回操作记录数 // 遍历结果集
while (rs.next()) {
//根据列名查询对应的值,也可以是位置序号
String name = rs.getString("name");
String age = rs.getString("age");
System.out.println(name);
System.out.println(age);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
psmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
05-11 16:25