package petsystem;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
public class Connectt {
private static BasicDataSource bds;
public static DataSource getDataSource() {
if (bds == null) {
// 1.创建加载读取数据库地址、账号、密码、驱动的流
InputStream is = Connectt.class.getClassLoader().getResourceAsStream("jdbc.properties");
// 2.创建Properties对象
Properties pp = new Properties();
try {
// 3.加载数据流
pp.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 4.获取数据
String url = pp.getProperty("url");
String user = pp.getProperty("user");
String password = pp.getProperty("password");
String driver = pp.getProperty("driver");
// 5.初始化连接池
bds = new BasicDataSource();
bds.setUrl(url);
bds.setUsername(user);
bds.setPassword(password);
bds.setDriverClassName(driver);
bds.setInitialSize(100);
bds.setMaxActive(100);
bds.setMaxIdle(50);
bds.setMinIdle(10);
bds.setMaxWait(2000);
}
return bds;
}
public static Connection getConnection() {
Connection conn;
try {
conn = getDataSource().getConnection();
return conn;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
数据库案例中创建连接池以及连接
于 2016-06-15 21:00:18 首次发布