This article describes the Java implementation method for database connection pooling. Share to everyone for your reference. as follows:
Package com.kyo.connection;
Import java.sql.Connection;
Import Java.sql.DatabaseMetaData;
Import Java.sql.Driver;
Import Java.sql.DriverManager;
Import java.sql.SQLException;
Import java.sql.Statement;
Import java.util.Enumeration;
Import Java.util.Vector;
public class ConnectionPool {private Connectionparam param;
Private String testtable = "";
Test table name that tests whether the connection is available, default no test table private Vector connections = null; The vector that holds the database connection in the connection pool, initially//null, where the object is pooledconnection type public void SetParam (Connectionparam param) {This.par
am = param;
Public Connectionparam GetParam () {return param;
}/** * constructor * * @param param/public connectionpool (Connectionparam param) {this.param = param; /** * * Get the name of the test database table * * @return The name of the test database table/public String gettesttable () {return This.testta
ble /** * * Set the name of the test table * * @param testtable * String Test table name/public void settesttable (String te
sttable) { this.testtable = testtable; /** * Create a database connection pool, the number of available connections in the connection pool is the value set in class member initialconnections/public synchronized void CreatePool () throws Ex ception {//Ensure connection pool is not created//If the connection pool has already been created, the vector connections that holds the connection will not be null if (connections!= null) {return;
Create, returns the driver class instance specified in the JDBC Driver Driver Driver = (Driver) class.forname (This.param.getDriver ())
. newinstance ()); Drivermanager.registerdriver (driver);
Registers the JDBC driver//Creates a vector to save the connection, initially with 0 elements connections = new vector ();
Creates a connection based on the value set in Initialconnections.
Createconnections (This.param.getMinConnection ()); SYSTEM.OUT.PRINTLN (The database connection pool was created successfully!)
"); /** * * Creates a specified number of database connections by Numconnections and places these connections into the connections vector * * @param numconnections * to create Number of database connections built */private void createconnections (int numconnections) throws SQLException {//loop create a specified number of database connections for (int x = 0; x < numconnections/x + +) {//whether the number of database connections in the pool has been maximized? The maximum value is the class memberMaxConnections, indicates that if MaxConnections//is 0 or negative, there is no limit to the number of connections.
If the number of connections has reached the maximum, that is, exit. if (this.param.getMaxConnection () > 0 && this.connections.size () >= this.param.getMaxConnection ())
{break;
//Add a new Pooledconnection object to connections vector//Add a connection to a connection pool (vector connections) try {
Connections.addelement (New Pooledconnection (Newconnection ())); catch (SQLException e) {System.out.println ("Failed to create database connection!")
"+ e.getmessage ());
throw new SQLException ();
SYSTEM.OUT.PRINTLN ("Database connection created ..."); }/** * * Create a new database connection and return it * * @return returns a newly created database connection/private Connection newconnection () throws SQLException {///Create a database connection Connection conn = Drivermanager.getconnection (This.param.getUrl (), This.param.
GetUser (), This.param.getPassword ());
If this is the first time a database connection is created, that is, check the database, get the number of//maximum client connections that this database allows to support//Connections.size () ==0 indicates that no connection has been created at this time if (connections.size () = = 0) {DatabaseMetaData metaData = Conn.getmetadata ();
int drivermaxconnections = Metadata.getmaxconnections (); The database returns a drivermaxconnections of 0, indicating that the database does not have the maximum//connection limit, or that the maximum connection limit for the database is not known//Drivermaxconnections is an integer returned, representing this database
Number of client connections allowed///If the maximum number of connections set in the connection pool is greater than the number of connections allowed by the database, the maximum//number of connections to the connection pool is the largest number of databases allowed if (Drivermaxconnections > 0 && this.param.getMaxConnection () > Drivermaxconnections) {this.param.setMaxConnection (drive
Rmaxconnections); } return conn;
Returns the new database connection created}/** * * Returns an available database connection by calling the Getfreeconnection () function, * * * If there is currently no database connection available, and more database connections are not able to create
* * Built (such as connection pool size limit), this function waits for a while to try to fetch again. * * @return return an available Database connection object/public synchronized Connection getconnection () throws SQLException {//Ensure that the connection Chi is Create if (connections = null) {return null;///connection pool not yet created, returns null} Connection conn = Getfreeconnection (); Get an available database connection//ASThere is currently no connection that can be used, that is, all connections are in use while (conn = = null) {//Wait a second to try waiting (250); conn = Getfreeconnection (); Try again until you get the available connection, if//getfreeconnection () returns null//It means that you cannot obtain the available connections after creating a batch of connections} return conn;//the available
Connection}/** * * This function returns an available database connection from the connection pool vector connections, if * * Currently there is no available database connection, this function is set according to Incrementalconnections
The value of * * creates several database connections and puts them into the connection pool. * * If all connections are still in use after creation, return NULL * * @return return an available database connection/private Connection getfreeconnection () throws S
qlexception {//Get an available database connection from the connection pool Connection conn = Findfreeconnection (); if (conn = null) {//If no connection is available in the current connection pool//Create some connection createconnections (this.param.getIncrementalConnections
));
Re-find out if there are available connections from the Pool conn = Findfreeconnection ();
if (conn = = null) {//If no connection is obtained after the connection is created, NULL return null is returned;
} return conn; /** * * Find all connections in the connection pool, find an available database connection, * * If no connection is available, return null * @return Returns an available database connection/private Connection findfreeconnection () throws SQLException {Connection conn = null;
Pooledconnection pconn = null;
Gets all objects in the connection pool Vector Enumeration enumerate = Connections.elements ();
Iterate through all the objects to see if there is a connection available while (Enumerate.hasmoreelements ()) {Pconn = (pooledconnection) enumerate.nextelement ();
if (!pconn.isbusy ()) {//If this object is not busy, get its database connection and set it to busy conn = Pconn.getconnection ();
Pconn.setbusy (TRUE); Test if this connection is available if (!testconnection (conn)) {//If this connection is not available, create a new connection,//and replace the unavailable connection object, and if the creation fails, return n
ull try {conn = newconnection (); catch (SQLException e) {System.out.println ("Failed to create database connection!")
"+ e.getmessage ());
return null;
} pconn.setconnection (conn); } break;
An available connection has been found, exit}} return conn;//the available connections found/** * * Test whether a connection is available, turn it off if not available, and return false *
* Otherwise, you can return true * * * * * @param conn * Database connection required to be tested * * @return return True to indicate that this connection is available, false indicates that it is not available */private Bo Olean Testconnection (Connection conn) {try {//Judge whether the test table exists if (Testtable.equals ("")) {//If the test table is empty, Try using the Setautocommit () method of this connection to determine if the connection is available (this method is only available in some databases, if not available,//throws an exception).
Note: The method using the test table is more reliable conn.setautocommit (true); else {///have test table when using Test table test//Check if this connection is valid Statement stmt = Conn.createstatem
ENT ();
Stmt.execute ("SELECT count (*) from" + testtable);
The catch (SQLException e) {///above throws an exception, this connection is not available, closes it, and returns false;
CloseConnection (conn);
return false;
}//Connection available, returns true return true;
/** * * This function returns a database connected to a connection pool and puts this connection to idle.
* * All database connections that are obtained using connection pooling should be returned when not using this connection.
* * @param need to return to the connection object in the connection pool/public void returnconnection (Connection conn) {//Ensure the connection pool exists, if the connection is not created (does not exist), return directly if (connections = = null) {System.OUT.PRINTLN ("Connection pool does not exist, cannot return this connection to the connection pool!");
Return
} pooledconnection pconn = null;
Enumeration enumerate = Connections.elements (); Traverse all connections in the connection pool to find the connection object to return while (Enumerate.hasmoreelements ()) {Pconn = (pooledconnection) enumerate.nexteleme
NT ();
First find the Connection object to return in the connection pool if (conn = Pconn.getconnection ()) {//found, set this connection to idle Pconn.setbusy (false);
Break /** * * * * Flush all connection objects in the connection pool * */public synchronized void Refreshconnections () throws Sqlexc
Eption {//Ensure connection pool innovation exists if (connections = = null) {System.out.println ("Connection pool does not exist, cannot be refreshed!");
Return
} pooledconnection pconn = null;
Enumeration enumerate = Connections.elements ();
while (Enumerate.hasmoreelements ()) {//Get a Connection object pconn = (pooledconnection) enumerate.nextelement ();
If the object is busy wait 5 seconds, 5 seconds after the direct refresh if (Pconn.isbusy ()) {Wait (5000);/5 sec}//Close this connection, replace it with a new connection. CloseConnection (Pconn.getconnection ());
Pconn.setconnection (Newconnection ());
Pconn.setbusy (FALSE);
}/** * * Closes all connections in the connection pool and empties the connection pool. * * Public synchronized void Closeconnectionpool () throws SQLException {//Ensure connection pool exists, if not present, returns if (connections = n
ull) {System.out.println ("Connection pool does not exist, cannot be closed!");
Return
} pooledconnection pconn = null;
Enumeration enumerate = Connections.elements ();
while (Enumerate.hasmoreelements ()) {Pconn = (pooledconnection) enumerate.nextelement (); If busy, wait 5 seconds if (Pconn.isbusy ()) {Wait (5000);//5 Seconds}//5 seconds to close it directly closeconnection (pCo
Nn.getconnection ());
Remove it from the connection pool vector connections.removeelement (pconn);
}//Set connection pool to NULL connections = NULL; /** * * Close a database connection * * @param database connection that needs to be closed * * private void CloseConnection (Connection conn) {try
{Conn.close (); catch (SQLException e) {System.out.println("Close Database connection error:" + e.getmessage ()); }/** * * Causes the program to wait for a given number of milliseconds * * @param the given number of milliseconds */private void Wait (int mseconds) {try {thre
Ad.sleep (Mseconds);
The class used internally by the catch (Interruptedexception e) {}} to hold the connection object in the connection pool has two members, one is a connection to the database, and the other is a flag that indicates whether this connection is in use. * * Class Pooledconnection {Connection Connection = null;//database connection Boolean busy = false;//Whether this connection is being used by default is not The//constructor is being used to Connection a Pooledconnection object public pooledconnection (Connection Connection) {this.
connection = connection;
//Returns the connection in this object public Connection getconnection () {return Connection;
}//Set for this object, connect public void SetConnection (Connection Connection) {this.connection = Connection;
///Get the object connection busy public boolean isbusy () {return busy;
}//Set the connection of the object is busy public void Setbusy (Boolean busy) {this.busy = busy;
}
}
}
I hope this article will help you with your Java programming.