JDBC 连接池
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
public class DbUtils {
private static String driver;
private static String url;
private static String user;
private static String password;
private static int initSize;
private static int maxActive;
private static BasicDataSource ds;
static{
ds=new BasicDataSource();
Properties cfg=new Properties();
try {
InputStream in=DbUtils.class.getClassLoader().
getResourceAsStream("db.properties");
cfg.load(in);
//初始化参数
driver=cfg.getProperty("jdbc.driver");
url=cfg.getProperty("jdbc.url");
user=cfg.getProperty("jdbc.user");
password=cfg.getProperty("jdbc.password");
initSize=Integer.parseInt(cfg.getProperty("initSize"));
maxActive=Integer.parseInt(cfg.getProperty("maxActive"));
in.close();
//初始化连接池
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(user);
ds.setPassword(password);
ds.setInitialSize(initSize);
ds.setMaxActive(maxActive);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
public static Connection getConnection(){
try {
Connection conn=ds.getConnection();
return conn;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
public static void close(Connection conn){
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
}
}
}
public static void rollback(Connection conn){
if (conn!=null) {
try {
conn.rollback();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}