java: database connection pool

concept

Let’s take an example. Suppose we open a restaurant. When a customer comes, we hire a waiter and fire him after using it. When the next customer comes again, we invite another waiter and fire him after using it.

Is this the scenario where we use JDBC to connect to the database now: get the link every time, and release it after use.

But this is obviously inappropriate, because every time you apply for a connection, you need to apply for memory at the bottom layer of the server, etc., which is very troublesome and time-consuming, so let’s go back to the restaurant example. Several waiters came to serve. The analogy to the thread pool is:

There is a pool that holds containers (collections) of database connections. After the system is initialized, the container is created, and some connection objects will be applied for in the container. When the user accesses the database, the connection object will be obtained from the container. After the user accesses it, the connection object will be returned to the pool.
insert image description here
Benefits:
1. Save resources
2. Efficient user access

accomplish

The connection pool is some rules defined by java. There is an interface DataSource (data source/connection pool) under javax.sql, which is implemented by the driver supplier.

The DataSource interface provides two methods:

  • Get connection: getConnection()
  • Return the connection: Connection.close(). If the connection object Connection is obtained from the connection pool, then calling the Connection.close() method will not close the connection, but return the connection.

Generally, we don’t implement the above methods, but database vendors can implement them.

  1. C3P0: database connection pool technology
  2. Druid: database connection pool implementation technology, provided by Alibaba

C3P0

  • step:
    1. Import jar package (two) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar,

      • Don't forget to import the database driver jar package
    2. Define the configuration file:

      • Name: c3p0.properties or c3p0-config.xml
      • Path: Just put the file directly in the src directory.
    3. Create a core object database connection pool object ComboPooledDataSource

    4. Get connection: getConnection

  • code:
//1.创建数据库连接池对象
DataSource ds  = new ComboPooledDataSource();
//2. 获取连接对象
Connection conn = ds.getConnection();

Example:
c3p0-config.xml

<c3p0-config>
  <!-- 使用默认的配置读取连接池对象 -->
  <default-config>
  	<!--  连接参数 -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/db4</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <!-- 连接池参数 -->
    <!--初始化申请的连接数量-->
    <property name="initialPoolSize">5</property>
    <!--最大的连接数量-->
    <property name="maxPoolSize">10</property>
    <!--超时时间-->
    <property name="checkoutTimeout">3000</property>
  </default-config>

  <named-config name="otherc3p0"> 
    <!--  连接参数 -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/db3</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">8</property>
    <property name="checkoutTimeout">1000</property>
  </named-config>
</c3p0-config>
package cn.xxx.datasource.c3p0;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * c3p0演示
 */
public class C3P0Demo2 {
    
    

    public static void main(String[] args) throws SQLException {
    
    
       /* //1. 获取DataSource,使用默认配置
        DataSource ds  = new ComboPooledDataSource();

        //2.获取连接

        for (int i = 1; i <= 11 ; i++) {
            Connection conn = ds.getConnection();
            System.out.println(i+":"+conn);

            if(i == 5){
                conn.close();//归还连接到连接池中
            }
        }*/

        //testNamedConfig();

    }


    public static void testNamedConfig() throws SQLException {
    
    
        // 1.1 获取DataSource,使用指定名称配置
        DataSource ds  = new ComboPooledDataSource("otherc3p0");
        //2.获取连接
        for (int i = 1; i <= 10 ; i++) {
    
    
            Connection conn = ds.getConnection();
            System.out.println(i+":"+conn);
        }
    }

}

Druid

step:

  1. Import the jar package druid-1.0.9.jar
  2. Define the configuration file:
    • It is in the form of properties
    • Can be called any name, can be placed in any directory
  3. Load the configuration file. Properties
  4. Get the database connection pool object: get DruidDataSourceFactory through the factory
  5. Get connection: getConnection

druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///db3
username=root
password=root
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000
package cn.xxx.datasource.druid;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

/**
 * Druid演示
 */
public class DruidDemo {
    
    
    public static void main(String[] args) throws Exception {
    
    
        //1.导入jar包
        //2.定义配置文件
        //3.加载配置文件
        Properties pro = new Properties();
        InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
        pro.load(is);
        //4.获取连接池对象
        DataSource ds = DruidDataSourceFactory.createDataSource(pro);
        //5.获取连接
        Connection conn = ds.getConnection();
        System.out.println(conn);

    }
}

example

Use JDBC utils to encapsulate connection pool Druid for connection

Define tool class

  1. Define a class JDBCUtils
  2. Provide static code blocks to load configuration files and initialize connection pool objects
  3. provide method
    1. Get connection method: Get a connection through the database connection pool
    2. release resources
    3. How to get the connection pool
package cn.xxx.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Druid连接池的工具类
 */
public class JDBCUtils {
    
    

    //1.定义成员变量 DataSource
    private static DataSource ds ;

    static{
    
    
        try {
    
    
            //1.加载配置文件
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2.获取DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
    
    
        return ds.getConnection();
    }

    /**
     * 释放资源
     */
    public static void close(Statement stmt,Connection conn){
    
    
       /* if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn != null){
            try {
                conn.close();//归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }*/

       close(null,stmt,conn);
    }


    public static void close(ResultSet rs , Statement stmt, Connection conn){
    
    


        if(rs != null){
    
    
            try {
    
    
                rs.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }


        if(stmt != null){
    
    
            try {
    
    
                stmt.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }

        if(conn != null){
    
    
            try {
    
    
                conn.close();//归还连接
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取连接池方法
     */

    public static DataSource getDataSource(){
    
    
        return  ds;
    }

}

package cn.xxx.datasource.druid;

import cn.itcast.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 使用新的工具类
 */
public class DruidDemo2 {
    
    

    public static void main(String[] args) {
    
    
        /*
         * 完成添加操作:给account表添加一条记录
         */
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
    
    
            //1.获取连接
            conn = JDBCUtils.getConnection();
            //2.定义sql
            String sql = "insert into account values(null,?,?)";
            //3.获取pstmt对象
            pstmt = conn.prepareStatement(sql);
            //4.给?赋值
            pstmt.setString(1,"王五");
            pstmt.setDouble(2,3000);
            //5.执行sql
            int count = pstmt.executeUpdate();
            System.out.println(count);
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            //6. 释放资源
            JDBCUtils.close(pstmt,conn);
        }
    }

}

Guess you like

Origin blog.csdn.net/weixin_43972437/article/details/132318864