这个问题在这里已有答案:
我正在设置一个新的服务器,并且想要为数据库操作创建连接池。因此,根据需要,我可以从池中获取连接,并且在使用之后我可以将该连接返回到池。我认为我已经完成了大部分任务,但是如何创建这些方法,这将从池中检索并返回连接。
我使用此代码进行数据库连接。
public class DBConnection
{
private static Session session;
private static Connection connection;
private static Properties properties;
private static void go(){
System.out.print("Establishing Connection with database.");
try
{
JSch jsch = new JSch();
session = jsch.getSession(
properties.getProperty("SERVER_USERNAME"),
properties.getProperty("SERVER_NAME"), 22);
session.setPassword(properties.getProperty("SERVER_PASSWORD"));
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
int assinged_port=session.setPortForwardingL(
Integer.parseInt(properties.getProperty("LOCAL_PORT")),
properties.getProperty("SERVER_HOST"),
Integer.parseInt(properties.getProperty("SERVER_PORT")));
}
catch(Exception e){System.err.print(e);}
}
private static void conn() {
if (session == null) { go(); }
final String bs="?rewriteBatchedStatements=true";
final String URL=properties.getProperty("DB_URL")+":"+
properties.getProperty("LOCAL_PORT")+"/"+
properties.getProperty("DB_NAME")+bs;
BasicDataSource basicDataSource=new BasicDataSource();
basicDataSource.setUrl(URL);
basicDataSource.setUsername(properties.getProperty("DB_USERNAME"));
basicDataSource.setPassword(properties.getProperty("DB_PASSWORD"));
basicDataSource.setDriverClassName(properties.getProperty("DB_DRIVER_CLASS"));
try {
connection = basicDataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConn(){
if (properties == null) {
try {
properties = new Properties();
FileInputStream fis = new FileInputStream(System.getProperty("user.dir").concat(File.separator).concat("DB.properties"));
properties.load(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection == null)
{
conn();
}
//System.out.println("Database connection established.");
return connection;
}
}
如何创建池和两个方法一个用于从池获取连接,另一个方法用于返回到池的连接。
您已经在使用连接池(假设您使用的是org.apache.commons.dbcp.BasicDataSource
或来自dbcp2
),真正的问题是您正在创建静态Connection
并且只返回该连接。
不要这样做,删除静态字段connection
,确保创建一次数据源并将其分配给静态字段,并在getConn
中无条件地调用数据源上的getConnection
。