Where to close java PreparedStatements and ResultSets?

后端 未结 13 2212
忘了有多久
忘了有多久 2020-11-29 02:26

Consider the code:

PreparedStatement ps = null;
ResultSet rs = null;
try {
  ps = conn.createStatement(myQueryString);
  rs = ps.executeQuery();
  // process         


        
13条回答
  •  一生所求
    2020-11-29 02:48

    If you're really hand-rolling your own jdbc it definitely gets messy. The close() in the finally needs to get wrapped with its own try catch, which, at the very least, is ugly. You can't skip the close, although the resources will get cleared when the connection is closed (which might not be right away, if you're using a pool). Actually, one of the main selling points of using a framework (e.g. hibernate) to manage your db access is to manage the connection and result set handling so you don't forget to close.

    You can do something simple like this, which at least hides the mess, and guarantees that you don't forget something.

    public static void close(ResultSet rs, Statement ps, Connection conn)
    {
        if (rs!=null)
        {
            try
            {
                rs.close();
    
            }
            catch(SQLException e)
            {
                logger.error("The result set cannot be closed.", e);
            }
        }
        if (ps != null)
        {
            try
            {
                ps.close();
            } catch (SQLException e)
            {
                logger.error("The statement cannot be closed.", e);
            }
        }
        if (conn != null)
        {
            try
            {
                conn.close();
            } catch (SQLException e)
            {
                logger.error("The data source connection cannot be closed.", e);
            }
        }
    
    }
    

    and then,

    finally {
        close(rs, ps, null); 
    }
    

提交回复
热议问题