1 1 public class DBCPTest { 2 2 /* 3 3 * 使用BasicDataSource類,通過url, 4 4 和diverClass,username,password, 5 5 幾個參數與數據庫建立連接,從而返回一個DataSource連接池對象 6 6 */ 7 7 public DataSource getDS() { 8 8 BasicDataSource ds = new BasicDataSource(); 9 9 ds.setDriverClassName("com.mysql.jdbc.Driver"); 10 10 ds.setUsername("root"); 11 11 ds.setPassword("4230"); 12 12 ds.setUrl("jdbc:mysql://localhost:3306/jdbcdemo"); 13 13 return ds; 14 14 15 15 } 16 16 17 17 /* 18 18 * 測試查詢,通過上面返回的DataSource連接池對象的 19 19 getConnection()方法創建一個Connection對象,其後步驟省略 20 20 */ 21 21 @Test 22 22 public void testDBCPTest() throws Exception { 23 23 24 24 Connection connec = getDS().getConnection(); 25 25 String sql = "SELECT * FROM student"; 26 26 PreparedStatement ps = connec.prepareStatement(sql); 27 27 ResultSet rSet = ps.executeQuery(); 28 28 while (rSet.next()) { 29 29 System.out.println(rSet.getLong(1) + "-" + rSet.getString(2) + "-" + rSet.getInt(3)); 30 30 } 31 31 JdbcUtil.close(rSet, ps, connec); 32 32 } 33 33 }