使用DBCP连接池对连接进行管理

 //需要引用的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 }

 

转载于:https://www.cnblogs.com/shenzhi/p/6880144.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值