先请看下边的程序:
package run;import java.sql.*;public class Test{
public static void main(String args[]){
Go x=new Go();

x.close();

}
}public class Go{
Connection conDB=null;

public Go(){
ResultSet reString = null;

try {
Class.forName(strDriver);
this.conDB = DriverManager.getConnection(strCon);

Statement stw1 = SatanRun.conDB.createStatement();

reString=stw1.executeQuery("Select * From info");

reString.close();
stw1.close();
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
System.out.println(e);
}
}

public void close(){
try {
this.conDB.close();
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
System.out.println(e);
}
}我 想问问就我上边的这个程序中的close()方法能完全关闭我开启的数据库连接吗

解决方案 »

  1.   

    public void close() throws Exception
    {
    if (rs!=null) {
                        rs.close();
                    }
    if (stmt!=null) {
                        stmt.close();
                    }
    if (conn!=null) {
                        conn.close();
                    }
    }我這樣寫的
      

  2.   

    请教tomy
    您的rs,stmt,conn都是申请的Connection吗
      

  3.   

    你可以这样认为 con>statement>resultset
      

  4.   

    楼主的写法可以,但是要和TOMMY那样先检查一下要关闭的东西是不是为NULL吧!
      

  5.   

    当Statement关闭时,其产生的ResultSet会被关闭,
    当Connection关闭时,其产生的Statement会被关闭。
    但这有个问题,在实际开发过程中我们会用到连接池(独立或容器提供),从连接池获取的Connection的close方法一般是不会实际关闭连接的,而是会将其返回连接池。所以,应该这样public void go(){
      Connection conn=null;
      Statement stmt=null;
      try{
        rs=...;
        .......
        close(rs);
      }catch(Exception ex){
        
      }finally{
        close(stmt);
        close(conn);    
      }
    }private void close(ResultSet rs){
       try{
         if(rs!=null){
            rs.close();
         }
       }catch(Exception e) {
       }
    }
    private void close(Statement st){
       try{
         if(st!=null){
            st.close();
         }
       }catch(Exception e) {
       }
    }
    private void close(Connection conn){
       try{
         if(conn!=null){
            conn.close();
         }
       }catch(Exception e) {
       }
    }
      

  6.   

    如果只是使用桥连接 关闭conncetion就可以了
    使用连接池的 怎么关闭不太清楚
      

  7.   

    关闭一定要放在finally{}里面。
      

  8.   

    如果要彻底关闭与数据库的链接会话要加finally{}的,虽然用conn.close();关闭了链接,但会话还是在的,所以要最后加上finally{}.
      

  9.   

    关闭一定要放在finally{}里面。