Where to close java PreparedStatements and ResultSets?

后端 未结 13 2205
忘了有多久
忘了有多久 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: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();
            }               
        }
    }
    

提交回复
热议问题