站内搜索: 请输入搜索关键词

当前页面: 开发资料首页JSP 专题请问这样写代码,数据库的连接能不能关闭

请问这样写代码,数据库的连接能不能关闭

摘要: 请问这样写代码,数据库的连接能不能关闭


第一获得连接的类的代码:
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class GetConnection {
private Properties props=null;
public GetConnection(){
this.props=new Properties();
FileInputStream propsIn;
try {//conn.properties写着连接数据库的各种参数
propsIn = new FileInputStream("config//conn.properties");
this.props.load(propsIn);
propsIn.close();
} catch (Exception e) {
e.printStackTrace();
}

}
public Connection getConn() throws Exception{
Class.forName(this.props.getProperty("driver-class"));
String url=this.props.getProperty("driver-url");
String user=this.props.getProperty("user");
String password=this.props.getProperty("password");
return DriverManager.getConnection(url,user,password);
}
}
第二个类利用第一个类获得连接
public TestCon{
Connection con=null;
public Connection getCon(){
try{
GetConnection gc=new GetConnection();
con=gc.getConn();
}catch(Exception e){}
return con;
}
public void close(){
try{
if(con!=null)
con.close();
}catch(Exception e){}
}
}
在testcon类调用close方法时数据库连接有没有被关闭,或者这样之关闭了那个连接的引用?
我没学过JAVA都是自学的,请高手指教


可以关闭


我这也有个关闭的函数,你可以看看
public synchronized void close(){
try{
if(rs!=null){
rs.close(); rs=null;
}
}catch(Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}
try{
if(stmt!=null){
stmt.close(); stmt=null;
}
}catch(Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}
try{
if(con!=null){
con.close(); con=null;
}
}catch(Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}
}


不一定能关闭
还是写到finally里面吧
抛个异常就完了


连接数据库的代码后面一定要用finally把connection关闭


up


up


可以关闭的
ttaallkk1(j2ee_lover) ( ) 信誉:100 Blog 2006-8-26 16:06:07 得分: 0



不一定能关闭
还是写到finally里面吧
抛个异常就完了



这个应该是在使用的时候用到,最后关闭,而不是在这个方法里面用finally


如果
propsIn = new FileInputStream("config//conn.properties");
this.props.load(propsIn);
这两个其中一个发生异常时就不能关闭。

如果正常的话就可以关闭。

一般都写在finally模块中


↑返回目录
前一篇: 问个菜鸟问题:
后一篇: 请问js怎么判断中英文啊?