C3P0连接池 和 DbUtil工具

连接池:

连接池: 存放多个连接 的集合 。
原理:
        连接池中有多个Connection连接,使用连接时可以从池中获取,使用完毕又归还到连接池,可以提高效率 .

目的 : 解决建立数据库连接耗费资源和时间很多的问题,提高性能。

java为数据库连接池提供了公共的接口: javax.sql. DataSource ;

C3P0连接池: (开源免费)

C3P0连接池实现了DataSource 接口 , 重写了getConnection方法 .
Connectino getConnection () : 尝试建立与此DataSource 对象所表示的数据源的连接。

C3P0Utils工具类:

使用步骤:

  1. 成员位置创建DataSource实现类对象ComboPooledDataSource
  2. 编写配置文件c3p0-config.xml(设置4大连接信息) , 必须放在src下面.
  3. 获取数据库连接对象Connection并返回.
  4. 释放资源.

c3p0-config.xml

<c3p0-config>
    <!-- 使用默认的配置读取连接池对象 -->
    <default-config>
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/数据库名字</property>
        <property name="user">用户名</property>
        <property name="password">密码</property>

        <!-- 连接池参数 -->
        <!-- 初始连接数 -->
        <property name="initialPoolSize">5</property>
        <!-- 最大连接数 -->
        <property name="maxPoolSize">10</property>
        <!-- 最大等待时间 -->
        <property name="checkoutTimeout">2000</property>
        <!-- 最大空闲回收时间 -->
        <property name="maxIdleTime">1000</property>
    </default-config>
</c3p0-config>

工具类代码实现:

public class C3P0UtilsXML {
    // 1. 在成员位置创建一个静态的ComboPooledDataSource对象
    private  static DataSource() dataSource = new ComboPooledDataSource();

    // 2. 创建一个方法在ComboPooledDataSource对象获取Connection并返回 .
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接对象失败.."+e);
        }
    }

    // 定义一个方法直接返回连接池 , 共QueryRunner使用
    public static DataSource getDataSource(){
        return dataSource;
    }

    //3.创建一个方法,用于释放资源
    public static void close(ResultSet rs, Statement stat, Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stat!=null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();//不是关闭conn,是把conn归还给连接池
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

DbUtils工具: 简化原生态jdbc6步.

需要导入jar包 : commons-dbutils-1.6.jar

三个核心功能:
       a.QueryRunner() : 用于执行CURD的sql语句.
       b.ResultSetHandler接口 , 用于接收查询的结果集.
       c.DbUtils类 , 用于释放Connection资源.

空参构造方法:

构造方法: 用的是同一个连接.
        QueryRunner():需要手动提供Connection .
普通方法:
        update(Connection conn ,Stirng sql , Object…params)
        query(Connection conn , String sql , ResultSetHandler , params)
自己提供的Connection , 需要释放资源: DbUtils.CloseQuietly( ) ;

带连接池的方法:

构造方法: 不能保证是同一个连接.
       QueryRunner(DataSource) : 参数传递了连接池,
       会自动从连接池中获取Connection使用完毕会自动把Connection归还给连接池 .
成员方法:
        update(String sql , Object…params) : 执行DML语句.
        query(String sql , ResultSetHandler , Object…params) 执行查询语句

实现步骤: 3步

a.创建QueryRunner对象 .
b.使用方法update/query执行sql语句,获取结果.
c.处理结果.

ResultSetHandler结果集:

a.BeanHandler(Class type): 传递javabean的class文件对象 , 取出第一行 .
   前提 : 必须要提供空参构造方法.
b.BeanListhandler: 把多行结果存储到List中.
c.ScalarHandler: 用于查询结果是一个单一的值(聚合函数).
d.ColumnListHandler:用于查询指定的列 , 不传默认是第一列.

案例:

public class Demo01DButils {
    // 使用DbUtils对数据库表中添加数据.
    @Test
    public void testInsert() throws SQLException {
        // 1. 创建QueryRunner对象.
        QueryRunner qr = new QueryRunner();
        // 2. 使用QueryRunner对象中的方法update/query执行sql语句, 获取结果.
        Connection conn = C3P0UtilsXML.getConnection();
        String sql = "INSERT INTO product(pid,pname,price,category_id) VALUES(?,?,?,?);";
        int i = qr.update(conn, sql, 14, "优乐美", 3, "c005");
        System.out.println(i+"行数据添加成功...");
        // 3. 释放资源 
        DbUtils.closeQuietly(conn);
    }

    // 使用Dbutils对数据库表中的数据进行修改.
    @Test
    public void testUpdate() throws SQLException {
        // 1. 创建QueryRunner对象.
        QueryRunner qr = new QueryRunner(C3P0UtilsXML.getDataSource());
        // 2. 使用QueryRunner对象中的方法update/query执行sql语句,
        String sql = "UPDATE product SET pname=?,price=? WHERE pid = ?;";
        int i = qr.update(sql, "阿萨姆", 4.5, 14);
        System.out.println(i+"行数据修改成功...");
    }

    // 使用Dbutils对数据库表中的数据进行删除.
    @Test
    public void testDelete() throws SQLException {
        // 1. 创建QueryRunner对象.
        QueryRunner qr = new QueryRunner(C3P0UtilsXML.getDataSource());
        // 2. 使用QueryRunner对象中的update / query方法执行sql语句.
        String sql = "DELETE FROM product WHERE pid IN(?,?,?,?,?,?);";
        int i = qr.update(sql, 9, 10, 11, 12, 13, 14);
        System.out.println(i+"行数据删除成功...");
    }

    @Test
    public void testBeanHandle() throws SQLException {
        // 1. 创建QueryRunner对象.
        QueryRunner qr = new QueryRunner(C3P0UtilsXML.getDataSource());
        // 2. 使用QueryRunner对象中的query方法. 执行sql语句.
        String sql = "select * from product ;";
        Product p = qr.query(sql, new BeanHandler<>(Product.class));
        // 3. 处理结果.
        System.out.println(p);
    }
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,需要在项目中导入c3p0相关的jar包,可以在maven中添加以下依赖: ```xml <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> ``` 然后,在项目中创建一个c3p0配置文件,例如命名为c3p0-config.xml,内容如下: ```xml <?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <!--初始化连接池时,连接池中连接的个数--> <initialPoolSize>3</initialPoolSize> <!--连接池最多保存的连接数--> <maxPoolSize>10</maxPoolSize> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数--> <acquireIncrement>3</acquireIncrement> <!--连接超时时间--> <checkoutTimeout>60000</checkoutTimeout> <!--当连接池中连接空闲时间大于idleConnectionTestPeriod所指定的时间时,c3p0则会测试连接池中的连接有效性。--> <idleConnectionTestPeriod>60</idleConnectionTestPeriod> <!--如果设为true那么在取得连接的同时将校验连接的有效性。建议使用idleConnectionTestPeriod或automaticTestTable等方法来提升连接测试的可靠性。--> <testConnectionOnCheckin>false</testConnectionOnCheckin> <!--如果设为true那么在归还连接的同时将校验连接的有效性。建议使用idleConnectionTestPeriod或automaticTestTable等方法来提升连接测试的可靠性。--> <testConnectionOnCheckout>false</testConnectionOnCheckout> <!--自动提交--> <autoCommitOnClose>true</autoCommitOnClose> <!--打印连接详细信息--> <debug>true</debug> <!--MySQL数据库的驱动程序--> <driverClass>com.mysql.jdbc.Driver</driverClass> <!--连接的URL--> <jdbcUrl>jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false</jdbcUrl> <!--用户名--> <user>root</user> <!--密码--> <password>123456</password> <!--定义了一个标准的数据库查询语句,用来测试连接池中连接的可用性,如果执行失败,则抛出SQLException异常,表示该连接已经不可用了。--> <preferredTestQuery>select 1</preferredTestQuery> </c3p0-config> ``` 其中,需要根据实际情况修改jdbcUrl、user和password等参数。 最后,在Java代码中使用c3p0连接池,示例代码如下: ```java public class DBUtil { //定义一个C3P0数据源 private static ComboPooledDataSource ds = new ComboPooledDataSource("mysql"); /** * 获取连接对象 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } /** * 关闭连接对象、Statement对象和ResultSet对象 */ public static void close(Connection conn, Statement stmt, ResultSet rs) { try { if(rs != null) { rs.close(); } if(stmt != null) { stmt.close(); } if(conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } ``` 在具体使用时,可以通过DBUtil.getConnection()方法获取连接对象,并通过DBUtil.close()方法关闭连接对象、Statement对象和ResultSet对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值