关闭Spring数据源对象的结果集和准备好的statment连接

时间:2013-10-15 07:38:32

标签: java spring-jdbc spring-orm

我对于春季F / W来说非常新。我在我的应用程序中使用spring jdbc和spring ORM作为持久层。我有一个疑问,在一个多次调用的方法中,我们是否需要关闭结果集对象和语句对象。 示例代码为:

public   void  savedata() throws Throwable
    {
        Connection connection = null;
        try 
            {
            int lastUpdated= jdbcTemplate.queryForInt("select serial_id from serial_details ");
        SerialUpdated=jdbcTemplate.queryForInt("select count(* ) from serial_usg  where serial_bill is null  " +
                    " and SURROGATE_KEY > "+lastUpdated);

            connection = dataSource.getConnection();
            String Query = "select * from serial_mst where serial_bill is null  and " +
                    "SURROGATE_KEY  > "+ lastUpdated ;
            PreparedStatement pStatement = connection.prepareStatement(Query);          
            ResultSet rs = pStatement.executeQuery();       
            while(rs.next()){
                String data     = rs.getString("serial_bill");                          
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }               
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection != null && !connection.isClosed()){
                connection.close();
                connection = null;
            }           
        } 

我的问题是,如果我多次调用此方法,那么我是否需要关闭语句和结果集方法,否则只有连接对象足以关闭。

1 个答案:

答案 0 :(得分:0)

仅关闭连接而不是结果集的一个问题是,如果您的连接管理代码使用连接池,connection.close()只会将连接放回池中。此外,某些数据库在服务器上有一个游标资源,除非明确关闭,否则将无法正确释放。

这是一个可以在finally块中使用的实用方法:

public static void closeEverything(ResultSet rs, Statement stmt,
        Connection con) {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) {
        }
    }
    if (stmt != null) {
        try {
            stmt.close();
        } catch (SQLException e) {
        }
    }
    if (con != null) {
        try {
            con.close();
        } catch (SQLException e) {
        }
    }
}