请教:用单例模式封装了数据库连接的connection,需要关闭吗?

lyp907093825 lyp907093825 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
请教:用单例模式封装了数据库连接的connection,需要关闭吗?如果关闭会不会出问题,比如说:A线程拿到了连接connection,B线程同时也拿到了。A的事务完成后提交了,把connection关闭,B线程会不会出问题?


package com.gzsoft.secondWeb.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* 单例的模式
* @author lyp
*
*/
public class DB {

private static Connection conn=null;
private static String driver;
private static String connectionURL;
private static String username;
private static String password;

static{
Properties p=new Properties();
InputStream in=DB.class.getClassLoader().getResourceAsStream("connection.properties");
try {
p.load(in);
driver=p.getProperty("driver");
connectionURL=p.getProperty("connection_URL");
username=p.getProperty("username");
password=p.getProperty("password");

} catch (IOException e) {
}

}

public static Connection getConnetion(){
if(conn==null){
try {

Class.forName(driver).newInstance();
DriverManager.getConnection(connectionURL,username,password);
System.out.print("success to connect to database!");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("can't find the Driver");
} catch (SQLException e) {
System.out.println("fail to connect to database!");
}

}
return conn;

}
public static void closeAll(ResultSet rs,PreparedStatement psmt,Connection conn){
if(rs!=null){
try {
rs.close();
rs=null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if(psmt!=null){
try {
psmt.close();
psmt=null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
conn=null;
} catch (SQLException e) {
e.printStackTrace();
}
}

}

public static void main(String[] args) {
System.out.println("driver:"+driver+" connURL:"+connectionURL+" username:"+username+" password:"+password);
getConnetion();
}

}


...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
lyp907093825
Web 开发 81,108 成员 341,721 内容