jdbc connection pool configuration

代码:import java.io.FileInputStream;import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.Properties;

import org.slf4j.Logger;

public class ConnPool {
    //Using the stored set of database connections LinkedList 
    Private  static LinkedList <Connection> = ConnPool new new LinkedList <Connection> (); 

    // loading the configuration file static code block 
    static { 
     // if the jar package runs reported here will find this abnormal file, the solution is as follows. Path String
. = ConnPool class . .GetClassLoader () getResource ( "db.properties" ) .getPath (); // solutions need to comment this line of code
     // InputStream in = PropertiesUtil.class.getClassLoader.getResourceAsStream ( "db.properties "); // open this line of code to solve the above problem
FileInputStream in; // adjustment programs need to comment this line of code to open more than solve
the try { in = new new FileInputStream (path);// open the above solutions require comment this line of code the Properties prop = new new the Properties (); prop.load (in); String Driver = prop.getProperty ( "Driver" ); String url = prop.getProperty ( "url" ); User String = prop.getProperty ( "User" ); String password = prop.getProperty ( "password" ); // initialize the database connection pool size number of connections int InitSize = the Integer.parseInt (prop.getProperty ( "InitSize" ) ); // load drivers Class.forName (driver); for (int0 = I; I <InitSize; I ++ ) { Connection Conn = the DriverManager.getConnection (URL, User, password); // add a connection in the list created System.out.println ( "initialize database connection pool, to create the first" + (i + 1) + "connections, added to the pool" ); connPool.add (Conn); } } the catch (IOException E) { e.printStackTrace (); } the catch (a ClassNotFoundException E) { e.printStackTrace ( ); } the catch (SQLException E) { e.printStackTrace (); } } / *Database connection * / public Connection the getConnection () throws SQLException { IF (connPool.size ()> 0 ) { // Get a connection from the collection Final Connection Conn = connPool.removeFirst (); // return proxies Connection of return (Connection) the Proxy.newProxyInstance (ConnPool. class .getClassLoader (), conn.getClass (). The getInterfaces (), new new of InvocationHandler () { public Object Invoke (Object Proxy, Method, Method, Object [] args) throws the Throwable { IF ( ! "close".equals (method.getName ())) { return Method.invoke (Conn, args); } the else { connPool.add (Conn); System.out.println ( "closes the current connection, the connection pool and returns the connection .. ....... " ); System.out.println ( " pool number of connections is "+ connPool.size ()); return null ; } } }); } the else { the throw new new a RuntimeException (" busy database, try again later ............ " ); } } public PrintWriter getLogWriter() throws SQLException { return null; } public void setLogWriter(PrintWriter out) throws SQLException { } public void setLoginTimeout(int seconds) throws SQLException { } public int getLoginTimeout() throws SQLException { return 0; } public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } public Object unwrap(Class iface) throws SQLException { return null; } public boolean isWrapperFor(Class iface) throws SQLException { return false; } public Connection getConnection(String username, String password) throws SQLException { return null; } }
Import the java.sql.Connection;
 Import the java.sql.ResultSet;
 Import java.sql.SQLException;
 Import the java.sql.Statement; 

public  class JdbcUtil { 

    // database connection pool 
    Private  static ConnPool ConnPool = new new ConnPool (); 

    / ** 
     obtaining a connection from the pool * 
     * @return 
     * @throws SQLException
      * / 
    public  static connection the getConnection () throws SQLException {
         return connPool.getConnection (); 
    } 

    / **  
     * close the connection
     *@param Conn 
     * @param ST 
     * @param RS 
     * @throws SQLException 
      * / 
    public  static  void CloseConnection (Connection Conn, the Statement ST, ResultSet RS) throws SQLException { 

        // Close ResultSet object store query results 
        IF (RS! = null ) { 
                rs.Close (); 
        } 

        // close Statement object 
        IF (ST =! null ) { 
                st.close (); 
        } 

        // close the connection 
        IF (Conn =! null){
                conn.close();
        }
    }

}

db.properties

driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/数据库名?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=TRUE
user = root
password = root
InitSize = 15

Call as follows:

JdbcUtil jdbcUtil = new JdbcUtil();
  String sql = " write SQL statements " ; 
  Connection Connection = null ; 
  of Statement of Statement = null ;    ResultSet resultSet = null ;
{the try 
  Connection = jdbcUtil.getConnection (); 
  Statement = Connection.createStatement (); 
  the resultSet = Statement.executeQuery (SQL);
    the while (ResultSet.next ()) { 
        String ID = resultSet.getString ( "ID" ); IF ( ! ID = null ) { // business logic can be written here      }     }   } the catch (Exception E) { 
            logger.error ( "data acquisition failure" , E); 
            MSG = createResultJson (. 1, "data acquisition failure!" ); 
   } the finally {
      the try
        
      


{   jdbcUtil.CloseConnection (Connection, Statement, the resultSet); // remember the last close the stream, or will create too many connections abnormalities reported } the catch (SQLException E) { // the TODO Auto-Generated Block the catch e.printStackTrace (); } }

 

Guess you like

Origin www.cnblogs.com/wangquanyi/p/11446004.html