使用JDBC过程中如何正确关闭connection

173 篇文章 16 订阅
23 篇文章 0 订阅

来看一段代码:

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 void close(ResultSet rs) throws SQLException {
    if (rs != null) {
        rs.close();
    }
}

public static void close(Statement stmt) throws SQLException {
    if (stmt != null) {
        stmt.close();
    }
}

public static void close(Connection conn) throws SQLException {
    if (conn != null) {
        conn.close();
    }
}

public static void closeQuietly(Connection conn) {
    try {
        close(conn);
    } catch (SQLException e) {
        //e.printStackTrace();
    }
}

public static void closeQuietly(ResultSet rs) {
    try {
        close(rs);
    } catch (SQLException e) {
        //e.printStackTrace();
    }
}

public static void closeQuietly(Statement stmt) {
    try {
        close(stmt);
    } catch (SQLException e) {
        //e.printStackTrace();
    }
}

public static void closeQuietly(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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

N3verL4nd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值