需要准备的jar包:
MySQL的jar包mysql-connector-java-5.1.39-bin目前是5.1.39版本:
http://dev.mysql.com/downloads/connector/j/
C3p0的2个包:
https://sourceforge.net/projects/c3p0/
c3p0-0.9.1.2.jar和c3p0-sources-0.9.1.2.jar
配置文件:c3p0-config.xml
名字必须为这个!
演示代码:
1.package cn.hncu.C3p0;
2.
3.import java.beans.PropertyVetoException;
4..import java.sql.Connection;
5..import java.sql.SQLException;
6.
7..import org.junit.Test;
8.
9..import com.mchange.v2.c3p0.ComboPooledDataSource;
10.
11..public class C3p0Demo {
12.
13. @Test
14. // 纯Java方法使用c3p0
15. public void C3p0Demo() throws PropertyVetoException, SQLException {
16. ComboPooledDataSource pool = new ComboPooledDataSource();
17. pool.setUser("root");// 用户姓名
18. pool.setPassword("1234");// 用户密码
19. pool.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/hncu?seUnicode=true&characterEncoding=utf- 8");// MySQL数据库连接url
20. pool.setDriverClass("com.mysql.jdbc.Driver");
21.
22. // pool可以调用set方法进行Connection池的配置
23.
24.
25. // 连接关闭之后,内存会被释放,下次取时会重新开(内存地址不共用)
26. for (int i = 0; i < 20; i++) {
27. Connection con = pool.getConnection();
28. System.out.println(i + ":" + con);
29. if (i % 2 == 0) {
30. con.close();
31. }
32. }
33. }
34.
35. @Test
36. // 演示采用配置文件的方式使用c3p0
37. public void C3p0PropertyDemo() throws SQLException {
38. ComboPooledDataSource pool = new ComboPooledDataSource();//空参,自动到classpath目录下面加载“c3p0-config.xml”配置文件- - -配置文件的存储位置和名称必须是这样,且使用“默认配置”
39. //ComboPooledDataSource pool = new ComboPooledDataSource("demo");//加载“c3p0-config.xml”文件中定义的“demo”这个配置元素
40. for(int i=0;i<25;i++){
41. Connection con = pool.getConnection();
42. System.out.println(i+":"+ con.hashCode());
43. }
44. }
45.
46.}
包装一下C3P0的Connection池
1. package cn.hncu.C3p0;
2.
3. import java.sql.Connection;
4. import java.sql.SQLException;
5.
6. import javax.sql.DataSource;
7.
8. import com.mchange.v2.c3p0.ComboPooledDataSource;
9.
10. public class C3p0Pool {
11. //我们的这个包装,只是为了把c3p0池做成让每个线程(客户端)获得的是同一个连接,方便做b/s框架下的事务
12. private static DataSource pool;
13. private static ThreadLocal<Connection> t = new ThreadLocal<Connection>();
14. static{
15. pool = new ComboPooledDataSource("demo");
16. //这里的参数视你的配置文件而定,也可以不写,用默认的配置
17. }
18.
19. public static DataSource getDataSource(){
20. return pool;
21. }
22.
23.
24. public static Connection getConnection() throws SQLException{
25. Connection con = t.get();
26. if(con==null){
27. con=pool.getConnection();
28. t.set(con);
29. }
30. return con;
31. }
32. }
---------------------
作者:谙忆
来源:CSDN
原文:https://blog.csdn.net/qq_26525215/article/details/52212260
版权声明:本文为博主原创文章,转载请附上博文链接!
网友评论