c3p0连接池的使用

C3P0:(★)
        hibernate和spring使用
        有自动回收空闲连接的功能.
        使用步骤:
            1.导入jar包(c3p0-0.9.1.2.jar)
            2.使用api
                a.硬编码(不推荐)
                    new ComboPooledDataSource()
                b.配置文件
                    配置文件的名称:c3p0.properties 或者 c3p0-config.xml
                    配置文件的路径:src下
                    配置文件中的名字要少用:c3p0.user()格式
                    编码只需要一句话
                        new ComboPooledDataSource()//使用默认的配置
                        new ComboPooledDataSource(String configName)//使用命名的配置 若配置的名字找不到,使用默认的配置
 
硬编码代码演示:
 
 1 import java.sql.Connection;
 2  
 3 import com.mchange.v2.c3p0.ComboPooledDataSource;
 4  
 5 public class Demo {
 6      public static void main(String[] args) throws Exception {
 7           //硬编码使用c3p0连接池
 8           ComboPooledDataSource cpd = new ComboPooledDataSource();
 9           //配置参数
10           cpd.setDriverClass("com.mysql.jdbc.Driver");
11           cpd.setJdbcUrl("jdbc:mysql://localhost:3306/test");
12           cpd.setUser("root");
13           cpd.setPassword("root");
14  
15           Connection conn = cpd.getConnection();
16           System.out.println(conn);
17      }
18 }
19 //输出显示:
20 com.mchange.v2.c3p0.impl.NewProxyConnection@ed17bee
 
配置文件编码代码演示:
 
1 //简单配置文件
2 c3p0.driverClass=com.mysql.jdbc.Driver
3 c3p0.jdbcUrl=jdbc:mysql://localhost:3306/test
4 c3p0.user=root
5 c3p0.password=root
 
 1 //测试代码:
 2 package day9_01.c3p0_test;
 3  
 4 import java.sql.Connection;
 5  
 6 import com.mchange.v2.c3p0.ComboPooledDataSource;
 7  
 8 public class C3p0Demo {
 9      public static void main(String[] args) throws Exception {
10           //将配置文件放在src目录下
11           //一句话获取链接
12           ComboPooledDataSource cpd = new ComboPooledDataSource();
13           Connection conn = cpd.getConnection();
14           System.out.println(conn);
15      }
16 }

 

 
 
 
 
posted @ 2017-09-01 21:42  赵安之  阅读(272)  评论(0编辑  收藏  举报