JDBC的数据库查询是怎么编写的?
JDBC数据库查询的编写步骤如下:
-
加载数据库驱动程序。使用Class.forName()方法加载数据库驱动程序。
-
建立数据库连接。使用DriverManager.getConnection()方法建立与数据库的连接。
-
创建Statement或PreparedStatement对象。使用Connection对象的createStatement()或prepareStatement()方法创建Statement或PreparedStatement对象。
-
执行SQL查询语句。使用Statement或PreparedStatement对象的executeQuery()方法执行SQL查询语句,并将查询结果保存在ResultSet对象中。
-
处理查询结果。使用ResultSet对象的getXXX()方法获取查询结果,并进行相应的处理。
-
关闭ResultSet、Statement和Connection对象。使用close()方法关闭ResultSet、Statement和Connection对象,释放资源。
示例代码:
// 加载数据库驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, user, password);
// 创建PreparedStatement对象
String sql = "SELECT * FROM user WHERE age > ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 20);
// 执行SQL查询语句
ResultSet rs = pstmt.executeQuery();
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println(id + ", " + name + ", " + age);
}
// 关闭ResultSet、PreparedStatement和Connection对象
rs.close();
pstmt.close();
conn.close();
``
原文地址: https://www.cveoy.top/t/topic/drWz 著作权归作者所有。请勿转载和采集!