JDBC数据库操作中如何保证最后关闭了所占用的资源——try用法的细节控制
在java对数据库的JDBC开发中,往往需要确认最后释放数据库的连接资源,避免连接池被占用。
传统的方法是:
连接数据库后,定义连接和语句,然后执行响应的sql语句,执行完毕后,用close()依次逆序关闭statement语句和连接。经典代码如下:
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(URL, UNAME, UPASS);
statement = connection.createStatement();
String sqlString = "insert into ...";//略
if (statement.executeUpdate(sqlString) > 0) {
System.out.println("插入成功");
}
}catch (SQLException e) {
....
}
finally {
try {
if (statement!=null) statement.close();
if (connection!=null) connection.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
在JDK8.0以后,只要把所需要关闭的资源在try{}中完成声明,在最后系统会自动依次关闭其中的资源。非常适合用于管理statement、resultRecords等数据库操作中产生的短时资源。
而对于connection,当需要连续操作数据库时,仍然建议放在try之外定义,并手动控制关闭。
代码如下:
Connection connection = null;
try {
Statement statement = null;//statement放在try中,结束后会自动关闭
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(URL, UNAME, UPASS);
statement = connection.createStatement();
String sqlString = "insert into ...";//略
if (statement.executeUpdate(sqlString) > 0) {
System.out.println("插入成功");
}
...//还可以完成更多的sql操作
}catch (SQLException e) {
....
}
finally {
try {
if (connection!=null) connection.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
Connection,也可以放入try{}中声明,将会在执行完毕后,全部由系统自动关闭。
例如:
代码如下:
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(URL, UNAME, UPASS);
Statement statement = connection.createStatement();//statement放在try中,结束后会自动关闭
String sqlString = "insert into ...";//略
if (statement.executeUpdate(sqlString) > 0) {
System.out.println("插入成功");
}
...//还可以完成更多的sql操作
}catch (SQLException e) {
....
}
finally {
System.out.println("系统关闭全部资源");
}

315

被折叠的 条评论
为什么被折叠?



