//需要引用的jar包有4个,分别是commons-pool2-2.4.2.jar、commons-dbcp2-2.1.1.jar、mysql-connector-java-5.1.42-bin.jar、commons-logging-1.2.jar
//缺少一个都会报错(Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/pool2/PooledObjectFactory)意思是找不到这个包
//需要自己去官网下这几个包
//连接池是通过BasicDataSource对象对连接池进行管理的,我们需要把关于数据库的关键信息设置给连接池,跟jdbc一样,初始化后,其余的操作就跟jdbc一样了
1 import java.sql.Connection;
2 import java.sql.ResultSet;
3 import java.sql.SQLException;
4 import java.sql.Statement;
5
6 import org.apache.commons.dbcp2.BasicDataSource;
7
8 /**
9 * @author 神余健芝
10 * @date 创建时间:2017年5月19日 下午7:00:04
11 */
12 public class DBPoolTest {
13
14 public static BasicDataSource ds = null;
15
16 public final static String DRIVER_NAME = "com.mysql.jdbc.Driver";
17 public final static String USER_NAME = "root";
18 public final static String PASSWORD = "123456";
19 public final static String DB_URL = "jdbc:mysql://localhost/shen_db?useUnicode=true&characterEncoding=utf-8&useSSL=false";
20
21 public static void dbpoolInit() {
22 ds = new BasicDataSource();
23 ds.setUrl(DB_URL);
24 ds.setDriverClassName(DRIVER_NAME);
25 ds.setUsername(USER_NAME);
26 ds.setPassword(PASSWORD);
27 }
28
29 public static void dbPoolTest() {
30 Connection conn = null;
31 Statement stmt = null;
32 ResultSet rs = null;
33 try {
34 conn = ds.getConnection();
35 stmt = conn.createStatement();
36 rs = stmt.executeQuery("select * from students");
37 while (rs.next()) {
38 System.out.println(rs.getString("name"));
39 }
40 } catch (SQLException e) {
41 e.printStackTrace();
42 } finally {
43 try {
44 if (conn != null)
45 conn.close();
46 if (stmt != null)
47 stmt.close();
48 if (rs != null)
49 rs.close();
50 } catch (SQLException e1) {
51 // 忽略
52 }
53
54 }
55 }
56
57 public static void main(String[] args) {
58 DBPoolTest.dbpoolInit();
59 DBPoolTest.dbPoolTest();
60 }
61
62 }