package ConnectionPool;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
public class ConnectionPooLDemo1 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
// 获取配置字符串
InputStream in = ConnectionPooLDemo1.class.getClassLoader().getResourceAsStream("db.properties");
Properties cfg = new Properties();
cfg.load(in);
String driver = cfg.getProperty("jdbc.driver");
String url = cfg.getProperty("jdbc.url");
String user = cfg.getProperty("jdbc.user");
String password = cfg.getProperty("jdbc.password");
int initialSize = 20;
int maxActive = 100;
int maxIdle = 10;
int minIdle = 5;
// 使用 BasicDataSource 类建立连接,创建连接池,并配置连接池
BasicDataSource bds = new BasicDataSource();
// 设置连接参数
bds.setDriverClassName(driver);
bds.setUrl(url);
bds.setUsername(user);
bds.setPassword(password);
// 设置管理参数
bds.setInitialSize(initialSize); // 初始化连接数
bds.setMaxActive(maxActive); // 设置最大连接数
bds.setMaxIdle(maxIdle); // 设置最大空闲连接数, 空闲连接:在数据库没有连接时,依然可以保持连接的数目。不会被清除,设置为 0 为没有限制
bds.setMinIdle(minIdle); // 设置最小空闲连接数
// 使用连接池连接数据库
Connection conn = bds.getConnection();
String sql = "SELECT * FROM jdbc_table_2";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()) {
System.out.println("id:" + rs.getInt("id") + " name:" + rs.getString("name"));
}
rs.close();
st.close();
// 归还连接
conn.close();
}
}