最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
提高数据库操作的可靠性
时间:2022-07-02 18:20:59 编辑:袖梨 来源:一聚教程网
Java中的数据库操作是比较频繁的,很多人在处理数据库操作时往往拿不准,只能保证程序正常运行下没有问题,但是很多都没有释放资源或者没有正确的释放资源,等到有问题又不知道怎么回事!这里给出一个通过JDBC操作数据库的简单例子, 希望有一定的参考价值,为了方便,通过数据库连接工厂获得连接。
有关连接工厂的代码:http://blog.*11*1*com.net/treeroot/archive/2004/09/24/115372.aspx
先看看下面这段代码,你是否觉得有问题?
try {
Connection conn = ConnectionFactory_JDBC2.getConnection();
Statement state = conn.createStatement();
ResultSet rs = state.executeQuery("select * from table");
//这里处理数据
rs.close();
state.close();
conn.close(); //有的连这一句都没有
}
catch(SQLException e){
//这里可以自己处理,也可以抛出
}
这里给出一个替代实现:
Connection conn = null;
Statement state = null;
ResultSet rs = null;
try {
conn = ConnectionFactory_JDBC2.getConnection();
state = conn.createStatement();
rs = state.executeQuery("select * from table");
//处理数据
}
catch(SQLException e){
//这里可以自己处理,也可以抛出
}
finally{
if(rs!=null){
try{rs.close();}catch(SQLException e){}
}
if(state!=null){
try{state.close();}catch(SQLException e){}
}
ConnectionFactory_JDBC2.closeConnection(conn);
}
这个实现好像更加复杂了,但是可靠性更高了,虽然第一段代码的实现一般不会有什么问题,确实很难会有问题(有时候想让Windows兰屏还真不容易),但是还是强烈建议通过finally释放你的资源,不要让潜在的危险存在!
有关连接工厂的代码:http://blog.*11*1*com.net/treeroot/archive/2004/09/24/115372.aspx
先看看下面这段代码,你是否觉得有问题?
try {
Connection conn = ConnectionFactory_JDBC2.getConnection();
Statement state = conn.createStatement();
ResultSet rs = state.executeQuery("select * from table");
//这里处理数据
rs.close();
state.close();
conn.close(); //有的连这一句都没有
}
catch(SQLException e){
//这里可以自己处理,也可以抛出
}
这里给出一个替代实现:
Connection conn = null;
Statement state = null;
ResultSet rs = null;
try {
conn = ConnectionFactory_JDBC2.getConnection();
state = conn.createStatement();
rs = state.executeQuery("select * from table");
//处理数据
}
catch(SQLException e){
//这里可以自己处理,也可以抛出
}
finally{
if(rs!=null){
try{rs.close();}catch(SQLException e){}
}
if(state!=null){
try{state.close();}catch(SQLException e){}
}
ConnectionFactory_JDBC2.closeConnection(conn);
}
这个实现好像更加复杂了,但是可靠性更高了,虽然第一段代码的实现一般不会有什么问题,确实很难会有问题(有时候想让Windows兰屏还真不容易),但是还是强烈建议通过finally释放你的资源,不要让潜在的危险存在!
相关文章
- 《笼子》机械师成就指南 04-15
- 漫蛙漫画登录页面免费漫画在线观看最新版本 - 漫蛙漫画苹果手机下载安装入口免费漫画阅读 04-15
- 《勇者斗恶龙7:重制版》主角转职路线推荐 04-15
- 《笼子》越往下成就指南 04-15
- uc浏览器网页版入口-uc浏览器网页版官方地址 04-15
- 对魔忍系列最新力作对魔忍特遣队正式上线 百位系列作角色全数登场 04-15