考虑一个简单的语句序列:
DataSource source=...
Connection conn=source.getConnection();
Statement stat=conn.createStatement();
String command="INSERT INTO Credentials VALUES('troosevelt','jabberwock');
stat.executeUpdate(command);
conn.close();
代码看起来很干净——打开一个连接,发出一个命令,立刻关闭连接。但有一个重大缺陷。如果一个方法调用抛出了一个异常,那么对close方法的调用永远不会发生!这种情况下,愤怒的用户可能沮丧地多次重新提交请求,而每次单击都会泄露另一个连接对象。为解决这个问题,应确保始终在finally块中放置对close的调用:
DataSource source=...
Connection conn=source.getConnection();
try{
Statement stat=conn.createStatement();
String command="INSERT INTO Credentials VALUES('troosevelt','jabberwock');
stat.executeUpdate(command);
}
finally{
conn.close();
}
该简单规则完全解决了连接泄露问题。
如果你没有将try/finally结构与其他任何异常处理代码结合,那么该规则是最有效的。尤其是,不要试图在同一个try块中捕获SQLException:
Connection conn=null;
try{
Statement stat=conn.createStatement();
String command="INSERT INTO Credentials VALUES('troosevelt','jabberwock');
stat.executeUpdate(command);
}
catch (SQLException){
//log error
}
finally{
conn.close(); //ERROR
}
这段代码存在两个微妙的问题。首先,如果调用getConnection抛出异常,那么conn仍是null,并且不能调用close。而且,调用close也可能抛出SQLException。替代的办法是使用两个独立的try块:
try{
Connection conn=source.getConnection();
try{
Statement stat=conn.createStatement();
String command="INSERT INTO Credentials VALUES('troosevelt','jabberwock');
stat.executeUpdate(command);
}
finally{
conn.close();
}
}
catch(SQLException)
{
//log error
}
内部的try块确保连接关闭。外面的try块确保将异常记录下来。