JDBC释放资源时遇到的问题
在学习JDBC时,看到教学视频的老师释放资源时使用三个try...catch..来关闭,产生了一些疑问。
问题:
为什么要用三个,全部写在一个可不可以。
回答:
不行,例子如下
boolean flag = true; //标志位,标志释放资源是否成功 if(resultSet != null){ try { resultSet.close(); preparedStatement.close(); con.close(); //GC回收 resultSet = null; preparedStatement = null; con = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } }
在上面的代码中,如果前面的.close()发生异常,则会进入到catch里面,剩下的.close()会关闭失败,所以不能这样写。
正确写法:
if(resultSet != null){ try { resultSet.close(); //GC回收 resultSet = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } if(preparedStatement != null){ try { preparedStatement.close(); //GC回收 preparedStatement = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } if(con != null){ try { con.close(); //GC回收 con = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } }
改进:
最后为了保证资源能够释放,还有在每个关闭语句的后面加一个finally,在finally里给要关闭的资源赋值为空。这样就算在关闭过程中抛异常不能及时关闭,但是由于赋值为空,没有引用该资源,在垃圾回收的时候也能够回收。
if(resultSet != null){ try { resultSet.close(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally{ //GC回收 resultSet = null; } } if(preparedStatement != null){ try { preparedStatement.close(); //GC回收 preparedStatement = null; } catch (SQLException throwables) { throwables.printStackTrace(); }finally{ //GC回收 preparedStatement = null; } } if(con != null){ try { con.close(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally{ //GC回收 con = null; } }
这样的方法可以确保资源会释放
参考资料:
https://blog.csdn.net/javy_codercoder/article/details/49178529
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现