配置c3p0数据源的方式有三种,分别是手动配置,xml文件配置和properties文件配置,这三种配置方式存在一种即可。
通常来讲,用文件配置更方便书写和阅读
配置如下:
注:*号部分写自己的配置
1.c3p0-config.xml配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <c3p0-config> 3 <default-config> 4 <property name ="driverClass">com.mysql.jdbc.Driver</property> 5 <property name ="jdbcUrl">jdbc:mysql://localhost:****/********</property> 6 <property name ="user">*********</property> 7 <property name ="password">***********</property> 8 </default-config> 9 </c3p0-config>
2.c3p0.properties配置
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:*****/*****
c3p0.user=******
c3p0.password=******
3.手动配置及连接测试
1 package JDBC;
2
3
4 import java.sql.Connection;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7 import java.sql.Statement;
8
9 import com.mchange.v2.c3p0.ComboPooledDataSource;
10
11 /**
12 * c3p0连接池
13 * @author Administrator
14 *
15 */
16 public class C3P0 {
17 public static void main(String[] args) {
18 Connection conn = null;
19 Statement stat = null;
20 ResultSet rs = null;
21 //创建一个c3p0数据源对象
22 ComboPooledDataSource scoure = new ComboPooledDataSource();
23 //利用对象读取配置信息
24 //注释掉这段代码后会去找配置文件,存在任意一个都可以成功
25 /*try {
26 scoure.setDriverClass("com.mysql.jdbc.Driver");
27 scoure.setJdbcUrl("jdbc:mysql://localhost:****/******");
28 scoure.setUser("********");
29 scoure.setPassword("*****");
30 } catch (Exception e) {
31 // TODO: handle exception
32 }*/
33
34 try {
35 conn = scoure.getConnection();
36 stat = conn.createStatement();
37 rs = stat.executeQuery("select * from student");
38 while(rs.next()){
39 int sno =rs.getInt("sno");
40 String sname = rs.getString("sname");
41 System.out.println("id:"+sno);
42 System.out.println("sname:"+sname);
43 }
44 } catch (SQLException e) {
45 // TODO Auto-generated catch block
46 e.printStackTrace();
47 }finally{
48 if(rs != null){
49 try {
50 rs.close();
51 } catch (Exception e2) {
52 e2.printStackTrace();
53 }finally{
54 rs = null;
55 }
56 }
57 if(stat != null){
58 try {
59 stat.close();
60 } catch (Exception e2) {
61 e2.printStackTrace();
62 }finally{
63 stat = null;
64 }
65 }
66 if(conn != null){
67 try {
68 conn.close();
69 } catch (Exception e2) {
70 e2.printStackTrace();
71 }finally{
72 conn = null;
73 }
74 }
75 }
76
77 }
78 }
测试结果:
