c3p0連接池的使用
阿新 • • 發佈:2017-09-01
步驟 sys spring jar包 目錄 static user print pri 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 [email protected]
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 }
c3p0連接池的使用