package com.gb.util;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class ConnectionPoolProp {
private static ComboPooledDataSource comboPooledDataSource;
public static final void initDBSource() {
Properties properties = new Properties();
try {
File file = new File(ConnectionPoolProp.class.getResource("/").getFile().toString() + "dbs.properties");
System.out.println(ConnectionPoolProp.class.getResource("/").getFile());
InputStream inputStream = new FileInputStream(file);
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
comboPooledDataSource = new ComboPooledDataSource();
try {
comboPooledDataSource.setDriverClass(properties.getProperty("driver"));
} catch (PropertyVetoException e) {
e.printStackTrace();
}
comboPooledDataSource.setJdbcUrl(properties.getProperty("url"));
comboPooledDataSource.setUser(properties.getProperty("user"));
comboPooledDataSource.setPassword(properties.getProperty("password"));
comboPooledDataSource.setMinPoolSize(Integer.parseInt(properties.getProperty("c3p0.minPoolSize")));
comboPooledDataSource.setMaxPoolSize(Integer.parseInt(properties.getProperty("c3p0.maxPoolSize")));
comboPooledDataSource.setInitialPoolSize(Integer.parseInt(properties.getProperty("c3p0.initPoolSize")));
comboPooledDataSource.setAcquireIncrement(Integer.parseInt(properties.getProperty("c3p0.acquireIncrement")));
comboPooledDataSource.setMaxStatements(Integer.parseInt(properties.getProperty("c3p0.maxStatements").trim()));
comboPooledDataSource.setMaxIdleTime(Integer.parseInt(properties.getProperty("c3p0.maxIdleTime")));
}
public static synchronized Connection getConnection() {
Connection conn = null;
try {
conn = comboPooledDataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
close(rs);
close(stmt);
close(conn);
}
public static void close(AutoCloseable close) {
if (null != close) {
try {
close.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void colsePool() {
if (null != comboPooledDataSource) {
comboPooledDataSource.close();
}
}
}
网友评论