package com.market.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class ConnectionManager {
private static DataSource datasource = null;
private static ThreadLocal<Connection> threadlocal = new ThreadLocal<Connection>();
static {
Properties prop = new Properties();
try {
prop.load(new FileInputStream("src//ConnectInfo.properties"));
datasource = BasicDataSourceFactory.createDataSource(prop);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn = threadlocal.get();
if (conn == null) {
try {
conn = datasource.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
threadlocal.set(conn);
}
return conn;
}
public static void closeConnection()
{
Connection conn=threadlocal.get();
if(conn!=null)
{
threadlocal.remove();
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
创建连接需要的包
评论区