The example of this article tells the method of Java's database connection pool. Share it for everyone for your reference. The specifics are as follows:
package com.kyo.connection; Import Java.sql.Connection; Import Java.SQL.DataBaseMetadata; Import Java.Sql.Driver; Import Java.DriverManager ; Import java.sql.sql.sqlexception; Import Java.sql.Statement; Import java.util.enumeration; Import Java.util.vector; Public Class ConnectionPool {Private Connectionparam; Table name, no test table private vector connector = null; / / / Stall the vector of the database connection in the connection pool, the initial time is // null. The objects stored in it are POOLEDCONNECTION PUBLIC VOID SETPARAM (ConnectionParam Param) {this.param = Param; etparam () {Return Param;} /** * Construction function * * @param Param * /Public ConnectionPool (ConnectionParam Param) {this.param = Param;} /** * * Get the name of the test database table of the test database table. */ public String GetTestTable () {Return This.Testtable;} / ** * * Set the name of the test table * * * @param testable * String Test table name * / Public VoidTettable (String TestTable) { this.Testtable = testtable;} / ** * 创建一个数据库连接池,连接池中的可用连接的数量采用类成员initialConnections 中设置的值*/ public synchronized void createPool() throws Exception { // 确保连接池没有创建// 如果连接池己经Created, the saving vector Connections will not be empty if (connection! = Null) {return; // If it is created, return} // The driver instance instance of driver driver = (driver) specified in JDBC Driver = (Driver) (Class.Forname (this.param.getdriver ()) .newinstance ()); DriverManager.registerDriver (driver); // Register the jdbc driver // Create a vector of saving connection, at the beginning, there is 0 elements Connections = n ew vector (); // Create a connection based on the value set in the initialconnection. CreateConnections (this.param.getminconconnection ()); System.out.println ("Database connection pool creation successfully!");} /** * * create a database connection specified by NumConnections, and put these connections into Connections into Vector Zhong * * * @Param NumConnections * The number of databases to be created */ Private Void CreateConnections (INT NUMCONNECTIONS) Throws Sqlexception {// Create a specified number of database connection for (int x = 0 0 ; x <numConnections; x ++) { / / / Does the number of database connecting to the pool have reached the maximum? The maximum value is by MaxConnections, pointing out that if MaxConnections // is 0 or negative, it means that there is no limit on the number of connections. // If the number of connections has reached the maximum, the exit is withdrawn. If (this.param.getMaxConnection ()> 0 &&THIS.CONNECTIONS.SIZE ()> = This.param.getmaxConnection () {Break;} // Add A New PooledConnection Object T T T o connections vector // add one connection to connection In the pool (in the vector connection), try {connections.addelement (New PooledConnection (newConnection ()));} Catch + e.getMessage ()); Throw new sqlexception ();} System.out.println ("Database connecting to create ...");} /** * * create a new database connection and return it to * *Rturn and return a new new The created database connection*/ Private Connection NewConnection () Throws Sqlexception {// Create a database connect to connection conn = DriverManager.getConnection (this.param.getUrl (), This .param.getUser (), this.param.getpassword () ); // If this is the first time to create a database connection, that is, check the database, and get the number of customer connections allowed by this database to support the support // connections.size () == 0 means that there is no connection to the creation of (connections to connections. .size () == 0) {databaseMetadata metadata = conn.getmetadata (); int driverMaxConnections = metadata.getMaxConnections (); // If CTIONS is 0, it means that this database does not have the maximum // connection limit, or the database The maximum connection limit is not known // DriverMaxConnections is an integer that returns, indicating that the number of connections in the connection pool allows customers to connect to The maximum number of IF (DriverMaxConnections> 0 &¶m.GetmaxConnection ()> DriverMaxConnection (DriverMaxConnection (DriverMaxConnection s);}} Return Conn; // Return to the new database connection created} /** * * Back a available database connection by calling the GetFreeConnection () function, * * If there is no available database connection, and more database connection cannot be created * * to build Try to get it again. * * @Return Return a available database connection object */ Public Synchronized Connection GetConnection () Throws Sqlexception {// Make sure that the connection Chi Ji is created if (Connections == NULL) { null; // The connection pool has not been created yet, then Return null} connection conn = getfreeconnection (); // Get a available database connection // If there is no connection that can be used at present, that is, all connections are in use (conn == null) Try the wait (250); conn = getfreeconnection (); // Re -try until the available connection, if // getfreeconnection () returns NULL // indicates that it cannot be obtained after the creation of a batch of connections} RETURN conn; // Returns the available connecting available}/** * * * This function returns a available database connection from the connected pool vector Connections. If * * does not currently use the database connection, this function sets * * * * * * * * * * * * * * * * * * * * Create several database connections and put them in the connection pool. * * If all the connections are still in use, return null * * * @Return Return a available database connection */ Private ConneConnection () Throws Sqlexception {// Obtain a available database connection from the connection pool Connection conn = FindFreeConnection (); if (conn == NULL) {// If there is no connection in the current connection pool // Create some connection CreateConnections (this.param.getINCREMENECTIONS ())); // Re -the pool Search whether There are available connecting connection () = findfreeconnection (); if (conn == null) {// If you still cannot get the available connection after the connection is created, return Null Return Null;}} Return conn; All the connections in the pool, find a available database connection, * * If there is no available connection, return Null * * * @Return Return a available database connection */ private connection findfreeconnection () Throws Sqlexception {Connection Conn = Null; PooledConnection Pconn = NULL; // Get all the objects in the connection pool vector enumeration enumerate = connections.elements (); // traversed all objects to see if there is an available connection. CTION) Enumerate .nextelement (); if (! PConn.isbusy ()) {// If this object is not busy, get its database connection and set it as a busy conn = pConn.getConnection (); // Test whether this connection can be using if (! TestConnection (conn)) {// If this connection cannot be used, create a new connection, // and replace this unavailable connection object. If the creation fails, return to NULL try {conn = newConnection ();} Catch (sqlexception e) {System.out.println ("Failure to create a database connection! " + e.getMessage ()); Return null;} pConn.setConnection (conn);} Break; // find a available connection, exit}} Return conn; // Back to find the available connection}/* * * * Test whether a connection is available. If it is not available, turn it off and return to False * *, otherwise you can use the True * * * * * * * * @Param CONN * database connection that needs to be tested * * *RTURN Return True to indicate that this connection can be available, false It means that you do not use*/ Private Boolean TestConnection (Connection Conn) {Try {// determine whether the test table exists if (testable.equals ("") {// If the test table is empty, try to use this connected setautocommit ()) Method // to determine whether the connection is available (this method is only available in some databases, if it is not available, // throw an exception). Note: The method of using the test table is more reliable .setAutoCommit (true);} else {// There is there any way Use the test table to test the test table // check if this connection is value statement stmt = conn.createStatement (); stmt.execute ("Select count (*) from" + testtable);} Catch Ception E) { / / / Throw abnormalities above. This connection is not available, close it, and return to false; closeConnection (conn); Return false;} // connection available, return True Return True; In the connection pool, and place this connection to idle. * * All database connections obtained by the connection pool should return it when the connection is not used. Void ReturnConnection (Connection Conn) {// Make sure that the connection pool exists. If the connection is not created (does not exist), return the (connections == null) {system.out.println ("The connection pool does not exist, and it cannot be returned to the connection to the connection to the connection to the connection to the connection to In the connection pool! "); Return;} PooledConnection PConn = Null; ENMERATION Enumerate = Connections.elements (); // All the connections in the connection pond, find the connection object WHILE (ENuMeerate.hasmo Reelements ()) { pConn = (PooledConnection) enumerate.nextElement (); // Find the connection object if the connection object to the connection pool if (conn == pConn.getConnection ()) {// Find it, set this connection to idle state PConn.Setbusy (FALSE); Bream;}} / ** * * Fix all the connection objects in the connection pool * * * * / public synchronized void refreshConnections () Throws sqlexception {// ensure that the connection pool innovation exists (C. onnections == null) {System.out.println ("The connection pool does not exist, it cannot be refreshed!"); Return;} PooledConnection pConn = null; enumeration enumerate = connelements (); Moreylements ()) {// Get a connection Object pConn = (pooledconnection) enumerate.nextelement (); // If the object is busy for 5 seconds, just refresh if (ponn.isbusy ()) {wait (5000); // Wait for 5 seconds} // Close This connection is replaced with a new connection. CloseConnection (pConn.getConnection ()); pConn.setConnection (newConnection ()); PConn.setBusy (FALSE);} /** * * all connections in the connection pool and clear the connection pool. */ Public Synchronized Void CloseConnectionPool () Throws Sqlexception {// Make sure that the connection pool exists. If it does not exist, return if (connection == null) {system.out.println (" You cannot close! "); Return ;} PooledConnection PConn = NULL; Enumeration Enumerate = Connections.elements (); WHILE (enumerate.hasmoreements ()) {pooledConnection) enumerate .sXtelement (); // If you are busy, wait for 5 seconds if (pConn.isbusy )) {wait (5000); // Wait for 5 seconds} // After 5 seconds, close its closeConnection (pConn.getConnection ()); // Delete it from the connection pool vector.removeelement (PCONN);} // The connection pool is empty connections = null;} / **** Turn off a database connection** @param Database connection* / private void closeconnection (connection continuity) {try {conn.close ();} CATC. h (sqlexception e) {system.out.println ("Close the database connecting error:" + e.getMessage ());} /**** to make the program wait for the given milliseconds** @param given the number given given* / Private Void Wait (int MSECONDS) {Try {Thread.Sleep (MSECONDS);} Catch (InterruptedException E) {} /** * * internal use to save the connected object in the connection pool. Members, one is the connection of the database, and the other is the sign that the connection is being used. */ Class PooledConnection {connection connection = null; // The database connection Boolean Busy = False; // Whether this connection is using is not using the constructor by default. Ection object Public PooledConnection (Connection Connection) {this.Connection = connection;} // Return to the connection of Public Connection GetConnection () {Return Connection;} // Set this object, connect Public Voice ection (connection connection) {this.connection = connection; } // Whether the object connection is busy Public Boolean isbusy () {Return Busy;} // The connection of the setting object is busy Public Void Setbusy (boolean busy) {this.busy = busy;}}}}}
It is hoped that this article is helpful to everyone's Java program design.