JDBC数据库连接池c3p0

package com.cy.pj.jdbc;

import com.cy.pj.jdbc.util.JDBCUtil;
import com.cy.pj.jdbc.util.JDBCUtil_V2;
import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 2022/9/24
 *
 * @Author : LaoWang
 */
public class JDBCdemo05 {
    public static void main(String[] args) {
//        method1();
        method2();
    }


    /**
     *  池的概念 -
     *  指的是内存中的一片空间(容器) 例如:集合,数组等
     *  已经使用的例如:常量池/线程池/连接池
     */
     /**  了解:
     *  简单举例一下常见的几种线程池:
     *  1、CachedThreadPool ——
     *  ExecutorService cachedPool = Executors.newCachedThreadPool();
     *  创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,
     *  若无可回收,则新建线程。
     *  2、FixedThreadPool ——
     *  ExecutorService fixedPool = Executors.newFixedThreadPool(5);
     *  创建一个定长线程池,可控制线程最大并发数,超出的线程会在你队列中等待,
     *  线程池的大小一旦达到最大值就会保持不变。
     *  如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。
     *  3、ScheduledThreadPool ——
     *  ExecutorService scheduledPool = Executors.newScheduledThreadPool(5);
     *  创建一个定长的线程池,支持定时即周期性任务执行。
     *  4、SingleThreadPool ——
     *  ExecutorService singlePool = Executors.newSingleThreadExecutor();
     *  创建一个单线程化的线程池,它只会用唯一 的工作线程来执行任务,
     *  保证所有任务按照指定顺序(FIFO)执行,如果这个唯一的线程因为异常结束,
     *  那么会有一个新的线程来替代它。
     *  此线程池保证所有任务的执行顺序按照任务的提交顺序执行。
     */

    /**
     * 连接池:就是将连接放在容器中,供整个程序共享,可以实现连接的复用。
     * 目的是减少创建和关闭的次数,从而提供程序执行的效率。
     * 在程序一启动时,就创建一批连接放在一个连接池中(容器),
     * 当用户需要连接时,就从连接池中获取一个连接对象。
     * 用完连接后,不要关闭,而是将连接再还回连接池中,
     * 这样一来,用来用去都是池中的这一批连接,就实现了连接的复用。
     */

    /**
     * 使用c3p0连接池 -
     * 所有的连接池都要实现一个接口 —— DataSource(数据源),
     * 因此连接池也被叫做数据源!
     * 创建数据库连接池对象 -
     * 使用DataSource接口的实现类 ComboPooledDataSource
     */


    /**
     * 创建连接池对象之后,通过线程池对象提供的方法,
     * 设置连接的数据库的基本信息。
     * 有三种方式:
     * 方式一 : 直接将参数通过set方法设置给c3p0连接池
     * 不推荐原因 -
     *  这种方式直接将参数写死在了程序中,后期一旦参数发生变化,就要修改程序。
     *  需要重新编译项目、重新发布项目,非常麻烦。
     */
    public static void method1()  {
/**      ComboPooledDataSource类中提供了set方法,设置连接数据库的基本信息
 *      setDriverClass("com.mysql.jdbc.Driver");
        setJdbcUrl( "jdbc:mysql:///hc_db?characterEncoding=utf-8" );
        setUser( "root" );
        setPassword( "root" );
 */
        //  1、创建连接池对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        //  2、
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
            comboPooledDataSource.setJdbcUrl("jdbc:mysql:///hc_db?characterEncoding=utf-8");
            comboPooledDataSource.setUser("root");
            comboPooledDataSource.setPassword("root");
            //从线程池中获取连接
            connection = comboPooledDataSource.getConnection();
            preparedStatement = connection.prepareStatement("SELECT * FROM USER ");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                Integer in = resultSet.getInt("id");
                String name = resultSet.getString("username");
                String password = resultSet.getString("password");
                System.out.println(in+name+password);
            }
        } catch (PropertyVetoException | SQLException e) {
            e.printStackTrace();
        }finally {
            //注意:此处关闭连接,并不是彻底关闭,而是将此连接对象connection归还给线程池
            JDBCUtil_V2.close(connection, preparedStatement, resultSet);
            System.out.println("已将连接归还给连接池");
        }
    }


    /**
     * 方式二 (推荐)
     * 将数据库连接参数,提取到一个 properties文件中
     * 注意:该文件必须放在src目录下
     * 该文件名必须为 : c3p0.properties
     * 这种方式由于是c3p0到指定的位置下寻找指定名称的properties文件,
     * 所以文件的位置必须是放在src或其他源码根目录下,
     * **文件名必须是c3p0.properties**。
     *
     * 文件内容为数据库的基本连接信息:
 c3p0.driverClass=com.mysql.jdbc.Driver
 c3p0.jdbcUrl=jdbc:mysql:///hc_db?characterEncoding=utf-8
 c3p0.user=root
 c3p0.password=root
     */
    public static void method2(){
        /**
         * 读取c3p0文件,从文件中获取数据库连接参数
         * 此时c3p0连接池会自动去对应的c3p0.properties配置文件中读取参数,
         * 所以文件名字必须是c3p0.properties ,否则可能出现异常问题。
         * 这里不必再编写JDBC工具类
         */
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = comboPooledDataSource.getConnection();
            preparedStatement = connection.prepareStatement("SELECT * FROM USER ");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                Integer id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                System.out.println(id+username+password);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
//            JDBCUtil.close(connection, preparedStatement, resultSet);
            comboPooledDataSource.close();//提供了close()方法,不需要再编写JDBC工具类
            System.out.println("已归还给连接池");
        }
    }


    /**
     * 方式三(推荐)
     * 将数据库连接参数提取到xml文件中
     * 文件必须放在src目录下
     * 文件名必须叫做 c0p0-config.xml
     * 这种方式由于是c3p0到指定的位置下寻找指定名称的xml文件,
     * 所以文件的位置必须是放在src或其他源码根目录下,
     * **文件名必须是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:///hc_db?characterEncoding=utf-8</property>
         <property name="user">root</property>
         <property name="password">root</property>
     </default-config>
 </c3p0-config>
     */
    public static void method3(){
        //此方法和method2一样,只需要删除properties文件即可
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = comboPooledDataSource.getConnection();
            preparedStatement = connection.prepareStatement("SELECT * FROM USER ");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                Integer id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                System.out.println(id+username+password);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            comboPooledDataSource.close();
            System.out.println("已归还给连接池");
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值