java 使用数据库连接池 操作mysql数据库

pom.xml中加入

<dependency>
            <groupId>commons-dbcpgroupId>
            <artifactId>commons-dbcpartifactId>
            <version>1.4version>
        dependency>
package com.lemon.utils.util;

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

import javax.sql.DataSource;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;

public class ConnectionPool {

    // JDBC Driver Name & Database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String JDBC_DB_URL = "jdbc:mysql://localhost:3306/ssm";

    // JDBC Database Credentials
    static final String JDBC_USER = "root";
    static final String JDBC_PASS = "root";
    private static DataSource dataSource = null;
    private static ConnectionPool jdbcObj = null;
    private static GenericObjectPool gPool = null;

    @SuppressWarnings("unused")
    public DataSource setUpPool() throws Exception {
        Class.forName(JDBC_DRIVER);

        // Creates an Instance of GenericObjectPool That Holds Our Pool of Connections Object!
        gPool = new GenericObjectPool();
        gPool.setMaxActive(5);

        // Creates a ConnectionFactory Object Which Will Be Use by the Pool to Create the Connection Object!
        ConnectionFactory cf = new DriverManagerConnectionFactory(JDBC_DB_URL, JDBC_USER, JDBC_PASS);

        // Creates a PoolableConnectionFactory That Will Wraps the Connection Object Created by the ConnectionFactory to Add Object Pooling Functionality!
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, gPool, null, null, false, true);
        return new PoolingDataSource(gPool);
    }

    public GenericObjectPool getConnectionPool() {
        return gPool;
    }

    // This Method Is Used To Print The Connection Pool Status
    private void printDbStatus() {
        System.out.println("Max.: " + getConnectionPool().getMaxActive() + "; Active: " + getConnectionPool().getNumActive() + "; Idle: " + getConnectionPool().getNumIdle());
    }
    //在静态代码块中创建数据库连接池
         static{
             try{
                 jdbcObj = new ConnectionPool();
                 dataSource = jdbcObj.setUpPool();

             }catch (Exception e) {
                 throw new ExceptionInInitializerError(e);
             }
         }
    public static Connection getJDBCConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        ResultSet rsObj = null;
        ResultSet rsObj2 = null;
        Connection connObj = null;
                Connection connObj2 = null;
        PreparedStatement pstmtObj = null;
                PreparedStatement pstmtObj2 = null;
        try {   
            jdbcObj.printDbStatus();

            // Performing Database Operation!
            System.out.println("\n=====Making A New Connection Object For Db Transaction=====\n");
            connObj = getJDBCConnection();
                        connObj2 = getJDBCConnection();
            jdbcObj.printDbStatus(); 

            pstmtObj = connObj.prepareStatement("SELECT * FROM blog");
                        pstmtObj2 = connObj2.prepareStatement("SELECT * FROM blog");
            rsObj = pstmtObj.executeQuery();
                        rsObj2 = pstmtObj2.executeQuery();
            while (rsObj.next()) {
                System.out.println("Username: " + rsObj.getString("title"));
            }
            System.out.println("\n=====Releasing Connection Object To Pool=====\n");            
        } catch(Exception sqlException) {
            sqlException.printStackTrace();
        } finally {
            try {
                // Closing ResultSet Object
                if(rsObj != null) {
                    rsObj.close();
                }
                // Closing PreparedStatement Object
                if(pstmtObj != null) {
                    pstmtObj.close();
                }
                // Closing Connection Object
                if(connObj != null) {
                    connObj.close();
                }
            } catch(Exception sqlException) {
                sqlException.printStackTrace();
            }
        }
        jdbcObj.printDbStatus();
    }
}

https://github.com/lebaminhquang/jdbcpool/blob/master/Documents/WebPooling/JdbcPool/src/main/java/com/jcg/jdbc/connection/pooling/ConnectionPool.java

https://github.com/joselopezjm/JDBCPool/blob/master/src/jmlv/org/JDBCPool/JDBCPool.java
https://www.cnblogs.com/xdp-gacl/p/4002804.html
https://blog.csdn.net/Alice_656/article/details/53283654

你可能感兴趣的:(java)