Where to close java PreparedStatements and ResultSets?

后端 未结 13 2147
忘了有多久
忘了有多久 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:45

    I use this..

    finally
    {
        if (ps != null) ps.close();
        if (rs != null) rs.close();
    }
    
    0 讨论(0)
  • 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); 
    }
    
    0 讨论(0)
  • 2020-11-29 02:53

    I know this is an old question, but just in case someone is looking for the answer, java now has the try-with-resouce solution.

    static String readFirstLineFromFile(String path) throws IOException {
          try (BufferedReader br =
                       new BufferedReader(new FileReader(path))) {
            return br.readLine();
        }
    }
    
    0 讨论(0)
  • 2020-11-29 02:53

    focus finally clause,

    finally {
       try {
          rs.close();
          ps.close();
       } catch (Exception e) {
          // Do something
       }
    }
    

    I think you have to modify 2 points.

    First, use try & catch again in fainlly clause.

    Second, do rs.close() before doing ps.close().

    fly1997@naver.com

    0 讨论(0)
  • 2020-11-29 02:57

    If your are using Java 7 you can use the improvements in the exception handling mechanisms in those classes that implement AutoCloseable (i.e. PreparedStatement, Resultset)

    You might also find this question interesting: Closing ResultSet in Java 7

    0 讨论(0)
  • 2020-11-29 02:57

    Probably an old (though simple) way to do things, but it still works:

    public class DatabaseTest {
    
        private Connection conn;    
        private Statement st;   
        private ResultSet rs;
        private PreparedStatement ps;
    
        public DatabaseTest() {
            // if needed
        }
    
        public String getSomethingFromDatabase(...) {
            String something = null;
    
            // code here
    
            try {
                // code here
    
            } catch(SQLException se) {
                se.printStackTrace();
    
            } finally { // will always execute even after a return statement
                closeDatabaseResources();
            }
    
            return something;
        }
    
        private void closeDatabaseResources() {
            try {
                if(conn != null) {
                    System.out.println("conn closed");
                    conn.close();
                }
    
                if(st != null) {
                    System.out.println("st closed");
                    st.close();
                }
    
                if(rs != null) {
                    System.out.println("rs closed");
                    rs.close();
                }
    
                if(ps != null) {
                    System.out.println("ps closed");
                    ps.close();
                }
    
            } catch(SQLException se) {
                se.printStackTrace();
            }               
        }
    }
    
    0 讨论(0)
提交回复
热议问题