JDBC 查询(读操作)数据库
步骤
- 注册
mysql的驱动 - 获得一个连接
- 创建一个查询
- 处理结果集
- 关闭连接
1. 注册mysql的驱动
Class.forName("com.mysql.jdbc.Driver");
2. 获得一个连接
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
3. 创建一个查询
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "param");
ResultSet rs = stmt.executeQuery();
4. 处理结果集
把一行数据映射成一个对象。
while (rs.next()) {
// 获取对应列名的值
rs.getString("...");
// ...
// 转化成对象
}
5.关闭连接
rs.close();
stmt.close();
conn.close();
// 在 finally 里也得释放,避免程序抛出异常而无法释放。
finally {
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}

浙公网安备 33010602011771号