分析&回答
- 1)加载(注册)数据库驱动(到JVM)。
- 2)建立(获取)数据库连接。
- 3)创建(获取)数据库操作对象。
- 4)定义操作的SQL语句。
- 5)执行数据库操作。
- 6)获取并操作结果集。
- 7)关闭对象,回收数据库资源(关闭结果集-->关闭数据库操作对象-->关闭连接)。
关闭外部资源的顺序应该和打开的顺序相反!
// 数据库驱动类名的字符串
String driver = "com.mysql.jdbc.Driver";
// 数据库连接串
String url = "jdbc:mysql://127.0.0.1:3306/jdbctest";
// 用户名
String username = "root";
// 密码
String password = "mysqladmin";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1、加载数据库驱动( 成功加载后,会将Driver类的实例注册到DriverManager类中)
Class.forName(driver);
// 2、获取数据库连接
conn = DriverManager.getConnection(url, username, password);
// 3、获取数据库操作对象
stmt = conn.createStatement();
// 4、定义操作的SQL语句
String sql = "select * from user where id = 100";
// 5、执行数据库操作
rs = stmt.executeQuery(sql);
// 6、获取并操作结果集
while (rs.next()) {
System.out.println(rs.getInt("id"));
System.out.println(rs.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 7、关闭对象,回收数据库资源
if (rs != null) { //关闭结果集对象
try {
rs.close();
} catch (SQLException e) {
log.error(ExceptionUtils.getFullStackTrace(e));
}
}
if (stmt != null) { // 关闭数据库操作对象
try {
stmt.close();
} catch (SQLException e) {
log.error(ExceptionUtils.getFullStackTrace(e));
}
}
if (conn != null) { // 关闭数据库连接对象
try {
if (!conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
log.error(ExceptionUtils.getFullStackTrace(e));
}
}
}
反思&扩展
使用JDBC操作数据库时,如何提升读取数据的性能?如何提升更新数据的性能?
- 提升读取数据的性能,可以指定通过结果集(ResultSet)对象的setFetchSize()方法指定每次抓取的记录数(典型的空间换时间策略);
- 提升更新数据的性能可以使用PreparedStatement语句构建批处理,将若干SQL语句置于一个批处理中执行。
喵呜面试助手: 一站式解决面试问题,你可以搜索微信小程序 [喵呜面试助手] 或关注 [喵呜刷题] -> 面试助手 免费刷题。如有好的面试知识或技巧期待您的共享!