使用前提:導(dǎo)包

方式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 {
//創(chuàng)建連接池對象
BasicDataSource bds = new BasicDataSource();
//設(shè)置連接參數(shù)
bds.setUrl(url);
bds.setUsername(user);
bds.setPassword(password);
bds.setDriverClassName(driverClass);
//設(shè)置連接池參數(shù)
bds.setInitialSize(5);//初始化連接個(gè)數(shù)
bds.setMaxActive(10);//最大連接個(gè)數(shù)
bds.setMaxWait(3000);//當(dāng)超過最大連接數(shù)的等候時(shí)間
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)使用工廠類來創(chuàng)建dbcp連接池對象(讀取配置文件方式)
Properties prop = new Properties();
//使用類路徑讀取配置文件
InputStream in = DbcpTest2.class.getResourceAsStream("/jdbc.properties");
//加載配置文件
prop.load(in);
BasicDataSource bds = (BasicDataSource)BasicDataSourceFactory.createDataSource(prop);
/**
* 讀取jdbc.properties文件內(nèi)容
* dbcp可以自動識別每個(gè)配置信息,但是約定前提: 配置文件的key名稱和設(shè)置方法的名稱保持一致!?。? */
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();
}
}
}