以下是我的代码段
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();
}
}
答案 0 :(得分:2)
您需要执行以下操作:
try {
//do you db logic here.
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
答案 1 :(得分: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();
}
}
}