Database connection pool-Druid tool class compilation and tuning and usage examples (super-full comments are afraid you will not understand)

1. Database connection pool

It is actually a container (collection) that is used to store database connections. When the system is initialized, this container will be created, and this container will apply for some connection objects (the number of applied connection objects can be modified in the configuration file ), when the user accesses the database, the connection object is directly obtained from the container. After the user access is completed, the connection object is put back into the container, thus achieving reuse (the traditional way is: create the connection object when using it, use Destroy after it is finished, so the efficiency is not high)

  • The advantages of using a database connection pool are:
    1. save resources
    2. More efficient when accessing the database

2. Steps to use Druid database connection pool

  1. Import the jar package

  2. Define the configuration file:

    • The configuration file is: *.properties, the name is unlimited, but it must end with .properties.
  3. write the code:

    1. Load configuration file
    2. Get the connection pool object
    3. Get connection

3. Examples of use (notes are very detailed!!!)

1. druid.properties configuration file

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8
username=root
password=itcast
# 初始化的连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000

2. Druid connection pool tool class-JDBCUtils

/**
* Druid连接池的工具类
 */

public class JDBCUtils {

// 1. 定义一个成员变量 DataSource
private static DataSource dataSource;

static {

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

}

/**
 * 获取连接的方法
 */
public static Connection getConnection() throws SQLException {
    // 从连接池中取一个连接对象
    return dataSource.getConnection();
}


/**
 *  释放资源
 *  执行DML语句的时候需要关闭 statement 和 connection
 * @param statement
 * @param connection
 */
public static void close(Statement statement , Connection connection){
    if(statement != null){
        try {
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    if(connection != null){
        try {
            connection.close();      // 归还到连接池中
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}

/**
 * 释放资源
 * 执行DQL语句的时候需要关闭 resultSet statement 和 connection
 * @param resultSet
 * @param statement
 * @param connection
 */
public static void close(ResultSet resultSet,Statement statement , Connection connection){
    if(resultSet != null){
        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

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

    if(connection != null){
        try {
            connection.close();      // 归还到连接池中
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }*/
	// 我们发现上面两个关闭的过程和DML关闭的过程一样,所以为了代码的简洁可以直接调用方法关闭
    close(statement,connection);
}

/**
 * 获取连接池的方法
 */
public static DataSource getDataSource(){
    return dataSource;
}
}

3. Examples of using Druid connection pool tools

/**
 * 使用新的工具类
 */

public class DruidUtilsDemo {
	public static void main(String[] args) {
    /**
     * 完成添加的操作 给 accout 表添加一条记录
     */
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {
        // 1. 获取连接
        connection = JDBCUtils.getConnection();
        // 2. 定义sql
        String sql = "insert into account value(null,?,?)";
        // 3. 获取
        preparedStatement = connection.prepareStatement(sql);
        // 4. 给?赋值
        preparedStatement.setString(1,"小白白");
        preparedStatement.setDouble(2,3000);
		// 执行sql,返回值是影响的行数
        int count = preparedStatement.executeUpdate();
        System.out.println(count);
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        // 6. 释放资源
        JDBCUtils.close(preparedStatement,connection);
    }
	}
}

If you don't understand, I suggest you refer to my other blog- complete JDBCUtils and login cases, and solve SQL injection problems. The preparation of the most basic JDBC tool classes guides you to think independently and complete the preparation of the JDBCUtils class independently.

Guess you like

Origin blog.csdn.net/qq_45796486/article/details/114640043