一、API使用:释放资源
### --- API使用:释放资源
~~~ 需要释放的对象:ResultSet 结果集,Statement 语句,Connection 连接
~~~ 释放原则:先开的后关,后开的先关。ResultSet ==> Statement ==> Connection
~~~ 放在哪个代码块中:finally 块
~~~ 与IO流一样,使用后的东西都需要关闭!关闭的顺序是先开后关, 先得到的后关闭,后得到的先关闭
![](https://i-blog.csdnimg.cn/blog_migrate/90eee74f89dd99c1ac3abe97498c6a52.png)
二、代码示例
public class JDBCDemo05 {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
//1.注册驱动(省略)
//2.获取连接
String url = "jdbc:mysql://localhost:3306/db4";
connection = DriverManager.getConnection(url, "root", "123456");
//3.获取 Statement对象
statement = connection.createStatement();
String sql = "select * from jdbc_user";
resultSet = statement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
/**
* 开启顺序: connection ==> statement => resultSet
* 关闭顺序: resultSet ==> statement ==> connection
*/
try {
connection.close();
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
三、步骤总结
### --- 步骤总结
——> 1. 获取驱动(可以省略)
——> 2. 获取连接
——> 3. 获取Statement对象
——> 4. 处理结果集(只在查询时处理)
——> 5. 释放资源
四、sql语句
package com.yanqi.jdbc05;
import java.sql.*;
public class JdbcDemo03 {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
//1.注册驱动 省略
//2.获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db4", "root", "123456");
//3.获取语句执行对象
statement = connection.createStatement();
//4.执行SQL
String sql = "select * from jdbc_user";
resultSet = statement.executeQuery(sql);
//5.处理结果集对象
} catch (SQLException e) {
e.printStackTrace();
}finally {
//finally 中的代码始终会执行
try {
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}