Recently, I started to develop a website with a powerful background. When using the connection pool, I felt that the use of the server's own connection pool was always limited. At the same time, in order to deepen the learning and research of Java. Write down the following connection pool class.
This connection pool provides the following functions;
1) initialize once and use it everywhere.
2) the powerful log function records every SQL action, including Connection, ResultSet, and Statement.
3) based on the number of connections, connections that have been released or timed out are automatically recycled.
4) flexible configuration. You can use a variety of JDBC drivers and support multiple drivers.
Update description:
1) added character set configuration items.
2) A debugging switch is added to facilitate debugging before use.
3) changed the Log date output format.
4) eliminate a bug in createStatement l (thanks to rouselion's usage feedback)
5) fixed the potential problem of the getXXX function of the encapsulated class.
Source code:
- // File: ***** <ConnectionManager. java> ****
- /*
- * @ Title connection pool
- * @ Author: zxg
- * @ Version 2.5
- * @ Memo: defines database connections and database connection pools.
- */
- PackageCom. dbaccess. dbpool;
- ImportJava. io .*;
- ImportJava. SQL .*;
- ImportJava. util .*;
- ImportCom. mysql. jdbc. Driver;
- Public ClassConnectionManager {
- Static PrivateConnectionManager instance;// Unique instance
- // Static private int clients;
- Static Private LongCheckperiod = 0;
- Private VectorDrivers =New Vector();
- Private HashtablePools =New Hashtable();
- Private TimerCheckConnTimer =New Timer();
- // Debug mode switch
- Private Static BooleanDebug =False;
- // Character Set Hasse table
- Static Private HashtableCharacters =New Hashtable();
- Static Private PrintWriterLog;
- /**
- * A unique instance is returned. If this method is called for the first time, an instance is created.
- *
- * @ Return ConnectionManager: unique instance
- */
- Static Synchronized PublicConnectionManager getInstance (){
- If(Instance =Null){
- Instance =NewConnectionManager ();
- }
- // Clients ++;
- ReturnInstance;
- }
- /**
- * The construction function is private to prevent other objects from creating instances of this class.
- */
- PrivateConnectionManager (){
- Init ();
- }
- /**
- * The read attribute is initialized.
- */
- Private VoidInit (){
- PropertiesDbProps =Null;
- Try{
- InputStreamIs = getClass (). getResourceAsStream ("db. properties ");
- DbProps =New Properties();
- DbProps. load (is );
- }
- Catch(ExceptionE ){
- E. printStackTrace ();
- System. Err. println ("attribute file cannot be read =" +
- "Make sure that db. properties is in the path specified by CLASSPATH ");
- Return;