C3p0的使用:
1.C3P0开源的连接池,需要导入开发的jar包
c3p0-0.9.1.2.jar
2.只要学习该对象,不管是手动编码还是配置文件,都使用同一个类 ComboPooledDataSource
ComboPooledDataSource类,手动设置参数的方法入下
ComboPooledDataSource()
setDriverClass()
setJdbcUrl()
- setUser()
setPassword()
3,重点掌握配置文件的方式
创建名称为c3p0-config.xml (名称必须是它) 文件存放在src的目录下 c3p0自动去加载该配置文件,满足上述的条件
例子:
1,xml文件配置如下:
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <!-- 默认的配置 --> <default-config> <!-- 元素,属性,文本 --> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///h_db</property> <property name="user">root</property> <property name="password">123456</property> </default-config> </c3p0-config>
2,DBUti类:
package org.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DBUtil { //获取C3p0连接池 private static ComboPooledDataSource dataSource = new ComboPooledDataSource(); //从连接池中获取连接 public static Connection getConnection() throws SQLException{ return dataSource.getConnection(); } //关闭数据库链接 public static void closeResource(Connection conn, Statement st, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void closeResource(Connection conn, PreparedStatement pst) { if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if(pst != null){ try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } } //测试连接是否成功 public static void main(String args[]) throws SQLException { Connection conn = dataSource.getConnection(); if(conn!=null){ System.out.println("成功!"); System.out.println(conn); }else{ System.out.println("失败!"); } } }
如果测试结果如下,则测试成功,否则测试失败: