|NO.Z.00082|——————————|BigDataEnd|——|Java&MySQL.JDBC.V07|——|MySQL.v07|Jdbc开发_释放资源|
一、API使用:释放资源
### --- API使用:释放资源
~~~ 需要释放的对象:ResultSet 结果集,Statement 语句,Connection 连接
~~~ 释放原则:先开的后关,后开的先关。ResultSet ==> Statement ==> Connection
~~~ 放在哪个代码块中:finally 块
~~~ 与IO流一样,使用后的东西都需要关闭!关闭的顺序是先开后关, 先得到的后关闭,后得到的先关闭

二、代码示例
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();
}
}
}
}
Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
——W.S.Landor
分类:
bdv005-mysql
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通