Database Connection Pool Druid Configuration

Keywords: Druid SQL Java

Druid is provided by the C3P0, and the specific operation steps are very similar to those of the C.

We will copy the downloaded Druid directly into the IDEA tool


Druid's configuration file is in the form of properties. Its configuration file can be called any name and can be placed in any directory. It needs to be loaded manually, and the configuration file of C3P0 can be loaded automatically as long as the name is fixed and the location is fixed.


Specific code implementation:

The name indicated by the red arrow is the name of the configuration file.
Let's write a tool class for Druid connection pool:

package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

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

/**
 * Druid Connection pool tool class
 *
 * */

public class JDBCUtils {
    //Define member variable DataSource
    private static DataSource ds;
    static {

        try {
            //Loading configuration files
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //Get DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //Get connection
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    //Release resources
    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();
            }
        }

    }
    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();
            }
        }

    }
    //Getting Connection Pool Method
    public static DataSource getDataSource(){
        return ds;
    }
}

Posted by max101 on Wed, 02 Oct 2019 01:29:05 -0700