Java 数据库连接池C3P0,德鲁伊(Druid)的详解

一、Java中数据库连接池的基本介绍
在这里插入图片描述

数据库连接池的示意图
在这里插入图片描述

二、数据库连接池的种类
在这里插入图片描述

三、C3P0数据库连接池的使用,代码如下

public class C3P0_ {
    
    
    //1.方式1:相关参数,在程序中指定user,url,password等
    @Test
    public void testC3P0_01() throws Exception {
    
    
        //1.创建一个数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();

        //2.通过配置mysql.properties获取相关连接信息
        //通过Properties,获取相关配置文件的信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        //获取相关的值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");

        //给数据源comboPooledDataSource设置相关的参数
        //注意:连接管理是由comboPooledDataSource来管理
        comboPooledDataSource.setDriverClass(driver);
        comboPooledDataSource.setJdbcUrl(url);
        comboPooledDataSource.setUser(user);
        comboPooledDataSource.setPassword(password);

        //初始化连接数
        comboPooledDataSource.setInitialPoolSize(10);

        //设置最大连接数
        comboPooledDataSource.setMaxPoolSize(50);
        //测试连接池的效率,测试对mysql 5000次操作
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
    
    
            Connection connection = comboPooledDataSource.getConnection();//这个方法就是从DataSource接口实现的
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("C3P0 5000次连接mysql耗时:" + (end - start));//C3P0 5000次连接mysql耗时:1038
    }

    //第二种方式,使用配置文件模板来完成
    //1.将c3p0提供的 拷贝到src目录下
    //2.该文件指定了连接数据库和连接池的相关参数
    @Test
    public void testC3P0_02() throws Exception {
    
    
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("ly_edu");
        //测试5000次连接mysql
        long start=System.currentTimeMillis();
        System.out.println("开始执行");
        for (int i = 0; i < 5000; i++) {
    
    
            Connection connection = comboPooledDataSource.getConnection();
            connection.close();
        }
        long end=System.currentTimeMillis();
        System.out.println("C3P0 5000次连接mysql耗时:" + (end - start));//C3P0 5000次连接mysql耗时:1026
    }
}

第二种方式需要使用配置模板来完成,将c3p0-config.xml拷贝到src目录下,就可以使用了,c3p0-config.xml代码如下

<c3p0-config>
    <!--数据库源名称代表连接池-->
    <named-config name="ly_edu">
        <!-- 使用默认的配置读取连接池对象-->
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/db_ly?serverTimezone=GMT</property>
        <property name="user">root</property>
        <property name="password">123456</property>

        <!-- 连接池参数 -->
        <!--每次增长的连接数-->
        <property name="acquireIncrement">5</property>
        <!-- 初始连接数 -->
        <property name="initialPoolSize">10</property>
        <!--最小连接数-->
        <property name="minPoolSize">5</property>
        <!-- 最大连接数 -->
        <property name="maxPoolSize">10</property>

        <!--可连接的最多的命令对象数-->
        <property name="maxStatements">5</property>

        <!--每个连接对象可连接的最多的命令对象数-->
        <property name="maxStatementsPerConnection">2</property>
    </named-config>
</c3p0-config>

四、德鲁伊(Druid)数据库连接池的使用,代码如下

public class Druid_ {
    
    
    @Test
    public void testDruid() throws Exception {
    
    
        //1.加入Druid jar包
        //2.加入配置文件,将该文件拷贝到项目的src目录下
        //3.创建Properties对象,读取配置文件
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\druid.properties"));

        //4.创建一个指定参数的数据库连接池
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        long start =System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
    
    
            Connection connection = dataSource.getConnection();
            connection.close();
        }
        long end =System.currentTimeMillis();
        System.out.println("Druid 5000次连接mysql耗时:" + (end - start));//Druid 5000次连接mysql耗时:3608
    }
}

五、将 Java 中封装JDBC连接到JDBCUtils工具类的详解 这边文章中的JDBCUtils工具类,更新为通过Druid数据库连接池得到连接和关闭资源。

JDBCUtilsByDruid工具类代码如下

//基于druid数据库连接池的工具类
public class JDBCUtilsByDruid {
    
    

    private static DataSource ds;

    //在静态代码块完成 ds初始化
    static {
    
    
        try {
    
    
            Properties properties = new Properties();
            properties.load(new FileInputStream("src\\druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    //编写getConnection方法
    public static Connection getConnection() throws SQLException {
    
    
        return ds.getConnection();
    }

    //关闭连接,在数据库连接池中,close不是真正的断掉连接
    //而是把使用的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) {
    
    
            throw new RuntimeException(e);
        }
    }
}

JDBCUtilsByDruid工具类的使用

public class JDBCUtilsByDruid_Use {
    
    
    @Test
    public void testSelect() {
    
    
        Connection connection = null;
        String sql = "SELECT id,name,borndate FROM ACTOR WHERE id = ?";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
    
    
            //1.得到连接
            connection = JDBCUtilsByDruid.getConnection();
            System.out.println(connection.getClass());//class com.alibaba.druid.pool.DruidPooledConnection
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 2);
            //执行得到结果集
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
    
    
                String name = resultSet.getString("name");
                int id = resultSet.getInt("id");
                Date borndate = resultSet.getDate("borndate");
                System.out.println(id + "\t" + name + "\t" + borndate);
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            JDBCUtilsByDruid.close(resultSet, preparedStatement, connection);
        }
    }
}

输出结果如下

class com.alibaba.druid.pool.DruidPooledConnection
2	王宝强	1980-01-03

猜你喜欢

转载自blog.csdn.net/lu202032/article/details/124590264