What is the suitable way to close the database connection in Java?

后端 未结 7 1758
盖世英雄少女心
盖世英雄少女心 2020-12-20 04:15

I tried to close the DB connection.But had a bit of confusion, say

ResultSet rs = null 

Whether I have to it close by

rs.c         


        
7条回答
  •  抹茶落季
    2020-12-20 04:44

    Those methods only close the ResultSet. You still have to close all Statement and Connection instances. I recommend doing so in a finally block. Something like,

    Connection conn = null;
    Statement stmt = null'
    ResultSet rs = null;
    try {
      conn = getConnection();
      stmt = conn.prepareStatement(sql);
      stmt.setString(1, "Hello"); 
      rs = stmt.executeQuery();
      while (rs.next()) {
        // ...
      }
    } catch (SQLException se) {
      se.printStackTrace();
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (stmt != null) {
        try {
          stmt.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (conn != null) {
        try {
          conn.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    

    If you use my Close utility the finally block could be,

    } finally {
      Close.close(rs, stmt, conn);
    }
    

提交回复
热议问题