1 public class DBCPTest {
2 /*
3 * 使用BasicDataSource类,通过url,
4 和diverClass,username,password,
5 几个参数与数据库建立连接,从而返回一个DataSource连接池对象
6 */
7 public DataSource getDS() {
8 BasicDataSource ds = new BasicDataSource();
9 ds.setDriverClassName("com.mysql.jdbc.Driver");
10 ds.setUsername("root");
11 ds.setPassword("4230");
12 ds.setUrl("jdbc:mysql://localhost:3306/jdbcdemo");
13 return ds;
14
15 }
16
17 /*
18 * 测试查询,通过上面返回的DataSource连接池对象的
19 getConnection()方法创建一个Connection对象,其后步骤省略
20 */
21 @Test
22 public void testDBCPTest() throws Exception {
23
24 Connection connec = getDS().getConnection();
25 String sql = "SELECT * FROM student";
26 PreparedStatement ps = connec.prepareStatement(sql);
27 ResultSet rSet = ps.executeQuery();
28 while (rSet.next()) {
29 System.out.println(rSet.getLong(1) + "-" + rSet.getString(2) + "-" + rSet.getInt(3));
30 }
31 JdbcUtil.close(rSet, ps, connec);
32 }
33 }