在关闭的时候 比如 private static Connection conn = null;
private static Statement stmt = null;
private static PreparedStatement pstm = null; 
private static ResultSet rs = null;
if(rs != null){
rs.close();
}
if(stmt != null){
stmt.close();
}
if(conn != null){
conn.close();
}
在关闭的时候 都要做一下非空判断 请问这是为什么呢??有什么易懂的方法吗??

解决方案 »

  1.   

    ....好问题 ~~~~连接数据库 会返回 
    rs  stmt conn对象,如果没有对象即( .. !=null)的判断,还需要关闭么
    if(conn == null)
    证明conn根本没open()何必close();
    ...
      

  2.   

    你的方法还是有问题,因为会抛出异常,造成后面的代码不会执行。比如 rs.close()抛出了异常,会造成 stat和 con 不会被关闭的。正确的做法
          if (rs != null) {
            try {
              rs.close();
            } catch (Exception ex) {}
          }
          if (pstat != null) {
            try {
              pstat.close();
            } catch (Exception ex) {}
          }
          if (con != null) {
            try {
              con.close();
            } catch (Exception ex) {}
          }
      

  3.   

    这样做是合理的一个空的引用不能用close()方法 为空的时候,关闭,就会抛出异常。
      

  4.   

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;public class DbOpt { public static void main(String[] args) {
    final String DRIVER = "com.mysql.jdbc.Driver";
    final String CONSTR = "jdbc:mysql://localhost:3306/mysqltest";
    final String USERNAME = "root";
    final String PASSWORD = "root";
    final String SQL = "SELECT id, name FROM employee";
    Connection conn = null;
    Statement stat = null;
    ResultSet rs = null;
    try {
    Class.forName(DRIVER);  //加载 JDBC 驱动
    conn = DriverManager.getConnection(CONSTR, USERNAME, PASSWORD);
    stat = conn.createStatement();
    rs = stat.executeQuery(SQL);
    while (rs.next()) {
    System.out.print(rs.getString(1));
    System.out.println("" + rs.getString("name"));
    }
    } catch (ClassNotFoundException e) {
    e.printStackTrace();  //一般要记录日志
    } catch (SQLException e) {
    e.printStackTrace();  //一般要记录日志
    } finally {
    //因为上面获取到数据库连接,创建语句对象,执行查询拿到结果集
    //的过程中都有可能抛出异常而使 close 方法执行不到,所以一般
    //在 finally 块中关闭所有打开的东西保证关闭会执行到。但如果
    //因抛异常而得不到数据库连接,那么 conn 还保持着空引用,这时
    //finally 中代码还是要执行的,所以要检测是否为空引用,避免
    //抛出 NullPointerException 异常。另外关闭的顺序应该与打开的
    //顺序相反,如下:
    if (rs != null) {
    try {
    rs.close();
    } catch (SQLException e) {
    e.printStackTrace();
    } finally {
    rs = null;  //为了尽早使结果集对象具备被GC回收的条件
    }
    }
    if (stat != null) {
    try {
    stat.close();
    } catch (SQLException e) {
    e.printStackTrace();
    } finally {
    stat = null;  //同上
    }
    }
    if (conn != null) {
    try {
    conn.close();
    } catch (SQLException e) {
    e.printStackTrace();
    } finally {
    conn = null;  //同上
    }
    }
    }
    }}