Java学习之JDBC两种连接池C3P0、Druid及工具类DBUtils的基本使用

Java学习-13-韩顺平老师

Java-JDBC快速入门

目录:

01-数据库连接池
02-封装JDBCUtilsByDruid
03-ApDBUtils工具类

数据库连接池

基本介绍:

1.预先再缓冲池中放入一定数量的连接,当需要建立连接时,只需要从“缓冲池”中取出一个,使用完毕后放回。
2.数据库连接池负责分配、管理和释放数据库连接,它允许多个程序重复的使用现有的数据库连接,而不是重新建立一个。
3.当应用程序向连接池请求的数量超过最大连接数量时,这些请求将被加入到等待队列。

连接池的种类:

1.DBC的数据库连接池使用 javax.DataSource来表示,DataSource只是个接口,该接口通常由第三方提供实现。
2.C3P0数据库连接池,速度相对较慢,稳定性不错(hubernate,spring)。
3.DBCP数据库连接池,速度相对C3P0较快,但不稳定。
4.Proxoo数据库连接池,有监控连接池状态的功能,稳定性较c3p0差一点BoneCP 数据库连接池,速度快。
5.**Druid(德鲁伊)**是阿里提供的数据库的连接池,集DBCP,C3P0,Proxool有点于一身的数据库连接池。
这里就演示C3P0和Druid(德鲁伊)

C3P0数据库连接池实现: 首相要将jar包引入到项目中,jar可官网下载

@SuppressWarnings({"all"})
public class C3P0_ {
    public static void main(String[] args) throws Exception {
        method01();
        method02();
    }
    // 方法一:手动设置连接参数
    public static void method01()throws PropertyVetoException, SQLException{
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        // 为连接池设置驱动
        cpds.setDriverClass("com.mysql.jdbc.Driver");
        // 设置连接池连接数据库的参数
        cpds.setJdbcUrl("jdbc:mysql://localhost:3306/zcc_test");
        cpds.setUser("root");
        cpds.setPassword("196174");
        // 设置初始化的连接数量
        cpds.setInitialPoolSize(10);
        // 设置最大连接数量
        cpds.setMaxPoolSize(50);
        // 测试连接速度
        long start = System.currentTimeMillis();
        for (int i = 0; i < 500000; i++) {
            Connection connection = cpds.getConnection();
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("C3P0 所用时间:" + (end-start)); //1612
    }
    // 方法二:使用配置文件创建连接池
    public static void method02() throws Exception{
    	// 这里填写的参数,必须要和配置文件中 <name-config name ="zcc_mysql"></name-config> 一致
        ComboPooledDataSource cpds = new ComboPooledDataSource("zcc_mysql");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 500000; i++) {
            Connection connection = cpds.getConnection();
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("C3P0 所用时间:" + (end-start)); // 1580
    }
}

配置文件如下:在src目录下创建文件名 c3p0-config.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<c3p0-config>
    <default-config>
        <name-config name ="zcc_mysql"></name-config>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/zcc_test</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">196174</property>

        <property name="acquireIncrement">3</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">5</property>
        <property name="maxPoolSize">50</property>
    </default-config>
</c3p0-config>

Druid(德鲁伊): 在项目中导入 Druid.jar包
下载链接: Druid.jar下载链接

public class Druid_ {
    public static void main(String[] args) throws Exception{
        // 1.项目中导入jar包
        // 2.加载配置文件
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\druid.properties"));
        // 获得一个连接池
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 500000; i++) {
            Connection connection = dataSource.getConnection();
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("C3P0 所用时间:" + (end-start)); //685 相比于C3P0 效率大大提升
    }
}

配置文件:在src目录下创建 druid.properties 配置文件

# druid.properties文件的配置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/zcc_test
username=root
password=196174
# 初始化连接数量
initialSize=10
# 最大连接数
maxActive=50
# 最大超时时间
maxWait=5000

封装JDBCUtilsByDruid:

用来创建连接和断开连接
public class JDBCUtilsByDruid {
    public static DataSource dataSource =null;

    static {
        try {
            // 初始化数据
            Properties properties = new Properties();
            properties.load(new FileInputStream("src\\druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

ApDBUtils工具类

>

下载链接: DBUtils下载链接

基本使用DButils(搭配上面封装的JDBCUtilsByDruid工具类):

public class DBUtils_ {
    public static void main(String[] args) throws SQLException {
        Connection connection = JDBCUtilsByDruid.getConnection();
        QueryRunner queryRunner = new QueryRunner();
        // 三种查询
        String sql ="select * from student where name = ?";
        String sql1 ="select * from student where name = ?";
        String sql2 ="select name from student where name = ?";
        // 第一参数:数据库连接, 第二个:sql语句
        // 第三个参数:返回多行多列,放回单行多列是 BeanHandler 返回单行单列是ScalarHandler
        List<Students> tomList = queryRunner.query(connection, sql, new BeanListHandler<>(Students.class), "tom");
        for (Students students :tomList) {
            System.out.println(students);
        }

        Students tom1 = queryRunner.query(connection, sql1, new BeanHandler<>(Students.class), "tom");
        System.out.println(tom1);
        Object tom = queryRunner.query(connection, sql1, new ScalarHandler(), "tom");
        System.out.println(tom);

        // 演示 DML create delete update
        String sql4 = "insert into students values(?,?)";
        String sql5 = "update students set name = ? where id = 3";
        queryRunner.update(connection,sql4,3,"jack");
        queryRunner.update(connection,sql5,"张山");
        JDBCUtilsByDruid.close(null,null,connection);
    }
}

JDBC学习小结,欢迎大家交流学习!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值