使用前提:导包
方式1:
public class DbcpTest {
private static String url = "jdbc:mysql://localhost:3306/employee_db";
private static String user = "root";
private static String password = "221121";
private static String driverClass = "com.mysql.jdbc.Driver";
static PreparedStatement st = null;
static ResultSet rs = null;
public static void main(String[] args) throws SQLException {
//创建连接池对象
BasicDataSource bds = new BasicDataSource();
//设置连接参数
bds.setUrl(url);
bds.setUsername(user);
bds.setPassword(password);
bds.setDriverClassName(driverClass);
//设置连接池参数
bds.setInitialSize(5);//初始化连接个数
bds.setMaxActive(10);//最大连接个数
bds.setMaxWait(3000);//当超过最大连接数的等候时间
try{
Connection conn = bds.getConnection();
st = conn.prepareStatement("select * from employee");
rs = st.executeQuery();
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getNString("name");
System.out.println(id+":"+name);
}
}catch (Exception e){
e.printStackTrace();
} finally{
bds.close();//把连接对象放回连接池R
}
}
}
方式2:
配置文件
public class DbcpTest2 {
static PreparedStatement st = null;
static ResultSet rs = null;
public static void main(String[] args) throws SQLException {
try {
//1)使用工厂类来创建dbcp连接池对象(读取配置文件方式)
Properties prop = new Properties();
//使用类路径读取配置文件
InputStream in = DbcpTest2.class.getResourceAsStream("/jdbc.properties");
//加载配置文件
prop.load(in);
BasicDataSource bds = (BasicDataSource)BasicDataSourceFactory.createDataSource(prop);
/**
* 读取jdbc.properties文件内容
* dbcp可以自动识别每个配置信息,但是约定前提: 配置文件的key名称和设置方法的名称保持一致!!!
*/
Connection conn = bds.getConnection();
st = conn.prepareStatement("select * from employee");
rs = st.executeQuery();
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getNString("name");
System.out.println(id+":"+name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}