0

下面是我的代码片段

public void closeConnection(){
    if(connection!=null){
    try {
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

我想在finally块中关闭此方法的连接,任何人都可以帮助...

我的要求是应该在这里打开连接......但connection.close()需要在finally块中......像这样:

public void closeConnection() {
    if(connection!=null){
    try {}
    finally {
        connection.close();
    }       
}
4

2 回答 2

2

您需要执行以下操作:

try {
  //do you db logic here.        
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    try {
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
于 2013-11-26T15:48:46.590 回答
1
You can do something like:-

public void closeConnection() {
    try{
    if(connection==null)
    {
    //Code to create connection and use DB operations
    }
}
    catch (SQLException e) {
            e.printStackTrace();
        }
    finally{
            if(connection!=null){
              try {
                connection.close();
              } catch (SQLException e) {
                e.printStackTrace();
              }
    }


        }
于 2013-11-26T16:11:28.283 回答