Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(“jdbc:mysql://127.0.0.1/test”,“root”,“123456”);
stmt = conn.prepareStatement(“select 1 from table”);
rs = stmt.executeQuery();
while(rs.next()){
System.out.println(“OK”);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(rs != null){
rs.close();
}
if(stmt != null){
stmt.close();
}
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
上面是一段很常见的jdbc代码.通常,我们都是在finally里释放资源,经常可以看到有人或者为了美观,或者为了省事,将rs.close(),stmt.close(),conn.close()放到同一个try,catch块中.事实上,这样子关闭是不够严谨是.如果rs.close()或者stmt.close()执行的时候抛出了异常,那么就不会执行conn.close(),也就没法正确关闭connection了.
为了保证connection可以正常关闭,我们稍微调整一下代码.如下:
try{
if(rs!= null){
rs.close();
}
}catch(SQLException e){
//handle the exception
}finally{
try{
if(stmt!= null){
stmt.close();
}
}catch(SQLException e){
//handle the exception
}finally{
try{
if(conn!= null){
conn.close();
}
}catch(SQLException e){
//handle the exception
}
}
}
这样的写法虽然正确,但还可以将代码再简洁些,就是在方法上声明throws SQLException,方法体中这样关闭。
try {
if(rs != null){
rs.close();//(1)
}
} finally{
try{
if(stmt != null){
stmt.close();//(2)
}
}finally{
if(conn != null){
conn.close();//(3)
}
}
}