来看一段代码:
import java.sql.*;
/**
* Created by N3verL4nd on 2017/4/17.
*/
public class JdbcDemo
{
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/weibo?"
+ "user=root&password=lgh123&useUnicode=true&characterEncoding=UTF8&useSSL=true";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
/* System.out.println(sql); */
rs = stmt.executeQuery("SELECT * FROM t_account");
while (rs.next()){
System.out.println(rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4));
}
rs.close();
System.out.println("ResultSet closed");
stmt.close();
System.out.println("Statement closed");
conn.close();
System.out.println("Connection closed");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
假如rs = stmt.executeQuery("SELECT * FROM s_account");我们查找一个不存在的表,就会出现异常:
而此时,
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;都没有被正确关闭。
正确的处理方式应该是:在finally语句块中执行关闭操作。
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// Do stuff
...
} catch (SQLException ex) {
// Exception handling stuff
...
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) { /* ignored */}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) { /* ignored */}
}
}当然如果可以确保不是空指针,则可以简写为:
} finally {
try { rs.close(); } catch (Exception e) { /* ignored */ }
try { ps.close(); } catch (Exception e) { /* ignored */ }
try { conn.close(); } catch (Exception e) { /* ignored */ }
}这对于我们来时还是过于冗长,我们可以使用
Apache Commons DbUtils 里的
DbUtils
} finally {
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(ps);
DbUtils.closeQuietly(conn);
}内部实现:
public static voidclose(ResultSet rs) throwsSQLException {
if(rs != null) {
rs.close();}
}
public static voidclose(Statement stmt) throwsSQLException {
if(stmt != null) {
stmt.close();}
}
public static voidclose(Connection conn) throwsSQLException {
if(conn != null) {
conn.close();}
}
public static voidcloseQuietly(Connection conn) {
try{
close(conn);} catch(SQLException e) {
//e.printStackTrace();}
}
public static voidcloseQuietly(ResultSet rs) {
try{
close(rs);} catch(SQLException e) {
//e.printStackTrace();}
}
public static voidcloseQuietly(Statement stmt) {
try{
close(stmt);} catch(SQLException e) {
//e.printStackTrace();}
}
public static voidcloseQuietly(Connection conn,Statement stmt,ResultSet rs) {
try{
closeQuietly(rs);} finally{
try{
closeQuietly(stmt);} finally{
closeQuietly(conn);}
}
}
参考:
http://stackoverflow.com/questions/2225221/closing-database-connections-in-java
http://www.cnblogs.com/hongten/archive/2011/03/29/1998311.html
http://www.cnblogs.com/jfqiu/p/3197014.html
https://shinesolutions.com/2007/08/04/how-to-close-jdbc-resources-properly-every-time/