使用C3P0连接池的工具类,DataSourceUtils工具类

首先导入C3P0jar包 ,dbutils包,mysql链接包
在这里插入图片描述再导入C3P0-Config.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:///web15</property>
	<property name="user">root</property>
	<property name="password">1204</property>
  </default-config>
  
  <named-config name="oracle"> 
    <property name="driverClass">com.mysql.jdbc.Driver</property>
	<property name="jdbcUrl">jdbc:mysql:///web_07</property>
	<property name="user">root</property>
	<property name="password">123</property>
  </named-config>
  

</c3p0-config>

最后编写工具类,工具类要放在utils包下

package utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {
    
    private static ComboPooledDataSource ds=new ComboPooledDataSource();
    
    /**
     * 获取数据源
     * @return 连接池
     */
    public static DataSource getDataSource(){
        return ds ;
    }
    
    /**
      * 释放资源
     * @param conn
     * @param st
     * @param rs
     */
     public static void CloseResource(Connection conn,Statement st , ResultSet rs){
         closeResultSet(rs);
         closeStaement(st);
         closeConn(conn);
     }
    
    /**
     * 获取连接
     * @return 连接
     * @throws SQLException 
     */
    public static Connection getConnection() throws SQLException{
        return ds.getConnection();
    }
    
    /**
      *释放连接 
     * @param conn
     *     连接
     */
     public static void closeConn(Connection conn){
         if(conn!=null){
             try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                conn = null ;
            }
         }
     }
     
     /**
      * 释放语句执行者
     * @param st
     * 语句执行者
     */
    public static void closeStaement(Statement st){
         if(st!=null){
             try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                st = null ;
            }
         }
     }
    
    /**
     * 释放结果集
     * @param rs
     * 结果集
     */
    public static void closeResultSet(ResultSet rs){
         if(rs!=null){
             try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                rs = null ;
            }
         }
     }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值