数据库连接池c3p0和DBUtils工具类

1,058 阅读5分钟

1、数据库连接池

a、概念

为了避免频繁的创建数据库连接,数据库连接池技术应运而生。数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用现有数据库连接,而不是重新建立。

连接使用完毕后,连接池将该Connection回收,并交付其他的线程使用,以减少创建和断开数据库连接的次数,提高数据库的访问效率。

b、DataSource接口

DataSource称之为数据源。它负责与数据库建立连接,并定义了返回为Connection对象的方法。

JDBD改c3p0步骤

  1. 导入响应的jar包 c3p0-0.9.1.2.jarmchange-commons-java-0.2.11.jar

  2. 在src根目录下创建c3p0-config.xml配置文件

    记得更改数据库的名字、密码等配置

    <?xml version="1.0" encoding="UTF-8"?>
    <c3p0-config>
       <!-- 默认配置,如果没有指定则使用这个配置 -->
        <default-config>
            <property name="user">root</property>
            <property name="password">root</property>
            <property name="jdbcUrl">jdbc:mysql://localhost:3306/kaoshi</property>
            <property name="driverClass">com.mysql.jdbc.Driver</property>
            <property name="checkoutTimeout">30000</property>
            <property name="idleConnectionTestPeriod">30</property>
            <property name="initialPoolSize">3</property>
            <property name="maxIdleTime">30</property>
            <property name="maxPoolSize">100</property>
            <property name="minPoolSize">2</property>
            <property name="maxStatements">200</property>
        </default-config>
      
    	<!-- 命名的配置,可以通过方法调用实现 -->
        <named-config name="mysql">
            <property name="user">root</property>
            <property name="password">root</property>
            <property name="jdbcUrl">jdbc:mysql://localhost:3306/studyproject</property>
            <property name="driverClass">com.mysql.jdbc.Driver</property>
            <!-- 如果池中数据连接不够时一次增长多少个 -->
            <property name="acquireIncrement">5</property>
            <!-- 初始化数据库连接池时连接的数量 -->
            <property name="initialPoolSize">20</property>
            <!-- 数据库连接池中的最大的数据库连接数 -->
            <property name="maxPoolSize">25</property>
            <!-- 数据库连接池中的最小的数据库连接数 -->
            <property name="minPoolSize">5</property>
        </named-config>
        
    </c3p0-config>
    
  3. 写一个util工具类,获取数据源

    package com.systom.util;
    
    import javax.sql.DataSource;
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    
    public class C3p0Utils {
        //定义数据源属性
    	private static DataSource ds;
    	
    	static {
    		//获取C3P0连接池对象
    		ds = new ComboPooledDataSource();
    	}
    	//提供公共方法返回数据源
    	public static DataSource getDataSource() {
    		return ds;
    	}
    }
    
  4. 使用c3p0获取数据库连接、是否释放资源由c3p0决定**(删掉释放资源的代码即可)**

    //使用c3p0获取连接
    con=C3p0Utils.getDataSource().getConnection();
    

DBUtils

DBUtils封装了JDBC的操作,核心功能如下: Dbutils三个核心功能介绍

  1. QueryRunner中提供对sql语句操作的API.
  2. ResultSetHandler接口,用于定义select操作后,怎样封装结果集.
  3. DbUtils类是一个工具类,定义了关闭资源与事务处理的方法

QueryRunner核心类:

  1. QueryRunner(DataSource ds) 传入参数为连接池
  2. update(String sql, Object… params),执行insert update delete操作
  3. query(String sql, ResultSetHandler rsh, Object… params) ,执行 select操作

ResultSetHandler结果集处理类

常用的两个:

BeanHandler ——将结果集中第一条记录封装到一个指定的javaBean中;

BeanListHandler——将结果集中每一条记录封装到指定的javaBean中,将这些javaBean再封装到List集合中

DBUtils使用

  1. 导入commons-dbutils-1.4.jar

  2. 创建QueryRunner对象,注意:实例化QueryRunner时需要传递数据源

    QueryRunner runner =new QueryRunner(C3p0Utils.getDataSource());
    
  3. 执行sql语句,选择对应类————————记得抛出异常

    //执行 select(查询)操作————返回list时使用BeanListHandler
    			//sql语句	 //将结果集封装到一个指定的javaBean中//对应sql中 ? 的参数,可多个
    runner.query(String sql, new BeanHandler(XXX.class), Object… params);
    
    //执行insert delete update (增、删、改)操作
    			//sql语句	   //对应sql中?的参数
    runner.update(String sql, Object… params);
    

代码实例

@Override
	public List<City> findCityAll() throws SQLException {
		//sql语句
		String sql = "select * from province_city";
		//创建QueryRunner对象,实例化QueryRunner时需要传递数据源
QueryRunner runner =new QueryRunner(C3p0Utils.getDataSource());
		//执行sql语句
		List<City> list=
            (List<City>)runner.query(sql, new BeanListHandler(City.class));
	
		return list;
	}

	@Override
	public int saveCity(City city) throws SQLException {
		
		String sql = "insert into province_city(province_name,capital_name,money,out_people,in_people) values(?,?,?,?,?) ";
        
		//创建QueryRunner对象,实例化QueryRunner时需要传递数据源
		QueryRunner runner =new QueryRunner(C3p0Utils.getDataSource());
		//执行sql语句
		int row=
            (int)runner.update(sql, city.getProvince_name(),city.getCapital_name(), city.getMoney(), city.getOut_people(), city.getIn_people());
				
		return row;
	}

写出通用工具类

package com.systop.util;


import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

public class DBUtilsDao {
    //将其中的方法都改为静态 static	目的:在类后面加个点 “.” 就可以使用方法
    
	/**
	 * 查询所有数据的公用方法,没有参数
	 * @param sql 查询sql语句
	 * @param clazz 返回的类型
	 * @return 集合
	 * @throws SQLException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <clazz> List<clazz> findAll(String sql, Class<?> clazz) throws SQLException {
		//创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
		//调用方法
		List<clazz> list = (List<clazz>) runner.query(sql, new BeanListHandler(clazz));
		return list;
	}
	
	/**
	 * 根据参数查询数据的公用方法
	 * @param sql sql语句,可以有参数,案例为 xxx where id = ? 
	 * @param clazz 返回类型
	 * @param params 参数集合
	 * @return 集合
	 * @throws SQLException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <clazz> List<clazz> findListByParams(String sql, Class<?> clazz, Object ... params) throws SQLException{
		//创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
		List<clazz> list = (List<clazz>) runner.query(sql, new BeanListHandler(clazz), params);
		return list;
	} 
	
	/**
	 * 根据参数查询数据的公用方法
	 * @param sql sql语句,可以有参数,案例为 xxx where id = ? 
	 * @param clazz 返回类型
	 * @param params 参数集合
	 * @return 对象
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public static <clazz> clazz findObjectByParams(String sql, Class<?> clazz, Object ... params) throws SQLException{
		//创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
		clazz c = (clazz) runner.query(sql, new BeanHandler<>(clazz), params);
		return c;
	} 
	
	/**
	 * 增删改方法的调用
	 * @param sql sql语句
	 * @param params 参数列表
	 * @return true成功,false失败
	 * @throws SQLException
	 */
	public  Boolean update(String sql,Object ... params) throws SQLException {
		//创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
		int rows = runner.update(sql, params);
		if(rows > 0) {
			return true;
		}
		return false;
	}
}

调用通用工具类实例

//根据相应功能进行调用即可
//展示分类
		public List<Admin> findAdminAll() throws SQLException{
			
			String sql = "select * from admin";
            										//要传入的是什么类
			List<Admin> list =DBUtilsDao.findAll(sql, Admin.class);	
			return list;	
			
		}