package com.minc.sms.datamap;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Vector;/**
<pre>This class maintians the specified pool of connections. 
It works in the following way:-Whenever  a client makes a call to get Connection  If there is a connection available
then return the connection.
If  connection is not available

If maximum connections are already in use

then loop till time out

If time out is over 
throw an exception

If connection is available
return connection

If maximum connections are not in use
create new connection add it to the pool and return it.

A user has to first get access to the pool of connections by calling getPool() or getPool(with parameters).
The first time any of these functions is called the pool is created with initial number of connections.
After this whenever a client makes a call the procedure is as stated above. Only the first call to getPool(with/whithout para)
is of consequence for creating connections as repeated calls are ignored once the pool is created. In that sense the .set methods
are there for future enhancements when creation of connection can be deffered or old connectiond severed to connect to different 
databases.getPool() without parameters is called when there is an XML file(read via ifg.utils.DOMUtil which actually reads it).<font color="Blue"><b>Examples</b></font>
<font color="Blue"><b>e.g. 1</b></font>  How to use when one wanst to read database parameters from dbconfig.xml ConnectionPool.setFilePath("C:/java/jswdk-1.0.1/leadserver/WEB-INF/jsp/beans/com/ifg/utils/");//directory where .xml and .dtd are store
ConnectionPool connectionPool=getPool(); //this will read .xml file and create the connection pool
connectionPool.printValues();//just a information dump of all the parameters read for debugging
ResultSet rset=null;
Connection con=connectionPool.getConnection() ; //gettting a single connection
Statement stmt=con.createStatement();//just demo e.g.
rset=stmt.executeQuery("select count(*) as cnt from HLLeadMaster");//just demo e.g.
rset.next();//just demo e.g.
int rows=rset.getInt("cnt");//just demo e.g.
System.out.println("cnt "+rows);//just demo e.g.
connectionPool.freeConnection(con); //don't forget to free connection
<font color="Blue"><b>e.g. 2</b></font> How to use when one wanst to to pass database parameters throught the constructor ConnectionPool connectionPool=getPool("jdbc:odbc:leadserver", "leadserver", "leadserver","sun.jdbc.odbc.JdbcOdbcDriver", 1, 5, 1 );
ResultSet rset=null;
Connection con=connectionPool.getConnection() ;
Statement stmt=con.createStatement();
rset=stmt.executeQuery("select count(*) as cnt from HLLeadMaster");
rset.next();
int rows=rset.getInt("cnt");
System.out.println("cnt is ---- "+rows);


*@author  Nosh & Naidu
</pre>*/

解决方案 »

  1.   

    public class ConnectionPool
    {
    private String URL = null; //means not initialized as yet.
    private String user = null; //means not initialized as yet.
    private String password = null; //means not initialized as yet.
    private int maxConns = -1; //means not initialized as yet.
    private int timeOut = 1; //means not initialized as yet.
    private int initConn = -1; //means not initialized as yet.
    private String dbDriver = null; //means not initialized as yet. private static ConnectionPool connectionPool;
    private static String filePath = "./";
    private static int checkedOut;
    private static Vector freeConnections = new Vector();
    /**To set the .xml configurations path e.g. jdbc:odbc:databaseName. Make sure you set this before calling getPool()

    *@param paraFilePath .xml path e.g "./" or "C:/com/ifg/utils/"*/ public static void setFilePath(String paraFilePath) throws Exception
    {
    if (isNullOrZeroLength(paraFilePath))
    throw new Exception("Null Values can't be passed as parameters");
    filePath = paraFilePath;
    } /**To set the database URL e.g. jdbc:odbc:databaseName.
    *@param URL of the database*/
    public void setURL(String url) throws Exception
    {
    if (isNullOrZeroLength(url))
    throw new Exception("Null Values can't be passed as parameters");
    ;
    this.URL = url;
    }
    /**To set the user of the database.
    *@param user of the database*/ public void setUser(String user) throws Exception
    {
    if (isNullOrZeroLength(user))
    throw new Exception("Null Values can't be passed as parameters");
    this.user = user;
    }
    /**To set the database password of the user set.
    *@param pswd for the database's user name specified.*/ public void setPassword(String pswd) throws Exception
    {
    if (isNullOrZeroLength(pswd))
    throw new Exception("Null Values can't be passed as parameters");
    this.password = pswd;
    }
    /**To set the maximum connections for the databsae to be maintained by this component.
    *@param maxcons maximum connections to be kept open.*/ public void setMaxConns(int maxcons) throws Exception
    {
    if (maxConns < 1)
    {
    throw new Exception("Maximum Connection count can't be 0");
    }
    this.maxConns = maxcons;
    }
    /**To set the time after a request (in seconds)when an exception is thrown in no connection is found .
    *@param t time in seconds*/
    public void setTimeOut(int t) throws Exception
    {
    if (timeOut < 1 || timeOut > 5)
    {
    throw new Exception("time out value should be between 1 to 5 seconds.");
    }
    this.timeOut = t;
    } /**To set the initial starting connections .
    *@param initC the initial connections to be opened*/
    public void setInitConn(int initC) throws Exception
    {
    if (initConn < 1)
    {
    throw new Exception("Initial Connection count can't be 0");
    }
    this.initConn = initC;
    } /**To set the driver .
    *@param dbDr the driver name to be used.*/
    public void setDBDriver(String dbDr) throws Exception
    {
    if (isNullOrZeroLength(dbDr))
    throw new Exception("Null Values can't be passed as parameters");
    ;
    this.dbDriver = dbDr;
    }
      

  2.   


    /**To .xml configuration files path 
    *@return Returns file path of .xml configuration file.*/ public static String getFilePath()
    {
    return filePath;
    } /**To get the database URL. 
    *@return Returns URL set for the database.*/ public String getURL()
    {
    return this.URL;
    }
    /**To get the database user name. 
    *@return Returns user name of the database.*/ public String getUser()
    {
    return this.user;
    }
    /**To get the database user name's password set. 
    *@return Returns password of the user.*/ public String getPassword()
    {
    return this.password;
    }
    /**To get the maximum connections set for the database. 
    *@return Returns the maximum connections.*/ public int getMaxConns()
    {
    return this.maxConns;
    }
    /**To get the time out set(in second) after which an exception is thrown if no connection is found. 
    *@return Returns the time out value.*/ public int getTimeOut()
    {
    return this.timeOut;
    } /**To get the initial connections which are going to be opened.
    *@return Returns the initial connections to be opened.*/
    public int getInitConn()
    {
    return this.initConn;
    } /**To set the driver .
    *@return Returns the driver name  used.*/
    public String getDBDriver()
    {
    return this.dbDriver;
    } /**<pre>This static function creates a pool for the first time it is called. Later calls simply give a referance
    to the client to the existing pool connectin object. The parameters for the pool are read from an existing XML file.
    *@return ConnectionPool object with live connections.
    </pre>*/
    public static ConnectionPool getPool()
    throws ClassNotFoundException, IOException, Exception
    {
    if (connectionPool == null)
    {
    connectionPool = new ConnectionPool();
    } //if first client calls then call the connection pooler return connectionPool;
    } /**<pre>This static function creates a pool for the first time it is called. Later calls simply give a referance
    to the client to the existing pool connectin object. The parameters for the pool are read from an existing XML file.
    *@return ConnectionPool object with live connections.
    </pre>*/
    public static ConnectionPool getReinitializedPool()
    throws ClassNotFoundException, IOException, Exception
    {
    connectionPool = new ConnectionPool(); return connectionPool;
    } /**<pre>This static function creates a pool for the first time it is called. Later calls simply give a referance
    to the client to the existing pool connectin object. The parameters have the meaning of the corresponding set functions
    of this class.
    *@return ConnectionPool object with live connections.
    </pre>*/ public static ConnectionPool getPool(
    String URL,
    String user,
    String password,
    String dbDriver,
    int maxConns,
    int timeOut,
    int initConn)
    throws ClassNotFoundException, IOException, Exception
    {
    if (isNullOrZeroLength(URL)
    || isNullOrZeroLength(user) /*|| isNullOrZeroLength(password)*/
    || isNullOrZeroLength(dbDriver))
    {
    throw new Exception("Null Values can't be passed as parameters");
    }
    if (initConn < 1)
    {
    throw new Exception("Initial Connection count can't be 0");
    }
    if (maxConns < 1)
    {
    throw new Exception("Maximum Connection count can't be 0");
    }
    if (timeOut < 1 || timeOut > 5)
    {
    throw new Exception("time out value should be between 1 to 5 seconds.");
    } if (connectionPool == null)
    {
    connectionPool = new ConnectionPool(initConn, dbDriver);
    connectionPool.URL = URL;
    connectionPool.user = user;
    connectionPool.password = password;
    connectionPool.maxConns = maxConns;
    connectionPool.timeOut = timeOut;
    connectionPool.initConn = initConn;
    connectionPool.dbDriver = dbDriver;
    } //if first client calls then call the connection pooler return connectionPool;
    }

      

  3.   

    private ConnectionPool()
    throws ClassNotFoundException, IOException, Exception
    {
    this.dbDriver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
    this.URL =
    "jdbc:microsoft:sqlserver://***;DatabaseName=MINCSMS";
    this.user = "sa";
    this.password = "Iwillforyouminc";
    this.maxConns = 21;
    this.timeOut = 30;
    this.timeOut = this.timeOut > 0 ? this.timeOut : 5;
    this.initConn = 5; Class.forName(this.dbDriver); initPool(this.initConn);
    }

    private ConnectionPool(int initConn, String driver)
    throws ClassNotFoundException, IOException, Exception
    {
    Class.forName(driver);
    initPool(initConn);
    } /*Actually creation of initial pool of connetions*/
    private void initPool(int initConns) throws Exception
    {
    for (int i = 0; i < initConns; i++)
    {
    try
    {
    Connection pc = newConnection();
    freeConnections.addElement(pc);
    }
    catch (SQLException e)
    {
    }
    }
    }

    /**<pre>This function returns a connectionn object from the pool it maintains.
    It will wait for the specified timeout. If it doesn't find a connection available in that time it will throw an exception.
    *@return Returns a connection object.
    </pre>*/
    public Connection getConnection() throws SQLException
    {
    try
    { return getConnection(timeOut * 1000);
    }
    catch (SQLException e)
    {
    throw e;
    }
    finally
    { /*System.out.println("In get Connection "+getStats());*/
    }
    } private synchronized Connection getConnection(long timeout)
    throws SQLException
    { // Get a pooled Connection from the cache or a new one.
    // Wait if all are checked out and the max limit has
    // been reached.
    long startTime = System.currentTimeMillis();
    long remaining = timeout;
    Connection conn = null;
    while ((conn = getPooledConnection()) == null)
    {
    try
    {
    wait(remaining);
    }
    catch (InterruptedException e)
    {
    }
    remaining = timeout - (System.currentTimeMillis() - startTime);
    if (remaining <= 0)
    {
    // Timeout has expired
    throw new SQLException("getConnection() timed-out");
    }
    } // Check if the Connection is still OK
    if (!isConnectionOK(conn))
    {
    // It was bad. Try again with the remaining timeout
    return getConnection(remaining);
    }
    checkedOut++;
    return conn;
    } private boolean isConnectionOK(Connection conn)
    {
    Statement testStmt = null;
    try
    {
    if (!conn.isClosed())
    {
    // Try to createStatement to see if it's really alive
    testStmt = conn.createStatement();
    testStmt.close();
    }
    else
    {
    return false;
    }
    }
    catch (SQLException e)
    {
    if (testStmt != null)
    {
    try
    {
    testStmt.close();
    }
    catch (SQLException se)
    {
    }
    }
    return false;
    }
    return true;
    } private Connection getPooledConnection() throws SQLException
    {
    Connection conn = null;
    if (freeConnections.size() > 0)
    {
    // Pick the first Connection in the Vector
    // to get round-robin usage
    conn = (Connection) freeConnections.firstElement();
    freeConnections.removeElementAt(0);
    }
    else if (maxConns == 0 || checkedOut < maxConns)
    {
    conn = newConnection();
    }
    return conn;
    } private Connection newConnection() throws SQLException
    { Connection conn = null;
    if (user == null)
    {
    conn = DriverManager.getConnection(URL);
    }
    else
    {
    conn = DriverManager.getConnection(URL, user, password);
    }
    return conn;
    }

      

  4.   

    /**<pre>A client should call this function when it no longer needs a connection. A cliend should not call close on the connection,
    but only on the statements or recordsets it has created through this connection.
    *@param conn the connection object which it had got.</pre>*/
    public synchronized void freeConnection(Connection conn)
    {
    // Put the connection at the end of the Vector
    freeConnections.addElement(conn);
    checkedOut--;
    notifyAll();
    }

    /**To release all the connection. Should only be called at the end of usage by the client.
    */
    public synchronized void release()
    {
    Enumeration allConnections = freeConnections.elements();
    while (allConnections.hasMoreElements())
    {
    Connection con = (Connection) allConnections.nextElement();
    try
    {
    con.close();
    }
    catch (SQLException e)
    {
    System.out.println("Couldn't close connection");
    }
    }
    freeConnections.removeAllElements();
    }

    /**Utility function returns the status of free connections, open connections, checked out connections etc.*/
    static public String getStats()
    {
    return "Total connections: "
    + (freeConnections.size() + checkedOut)
    + " Available: "
    + freeConnections.size()
    + " Checked-out: "
    + checkedOut;
    }

    void printValues()
    { System.out.println("getURL() " + getURL());
    System.out.println("getUser() " + getUser());
    System.out.println("getPassword() " + getPassword());
    System.out.println("getMaxConns() " + getMaxConns());
    System.out.println("getTimeOut() " + getTimeOut());
    System.out.println("getInitConn() " + getInitConn());
    System.out.println("getDBDriver() " + getDBDriver());
    }

    protected void finalize()
    {
    System.out.println("In finalize" + ConnectionPool.getStats());
    }

    /**Utility function, to check whether a parameter passed is NULL or zero length string.
    *@param para is the string that is passed.
    *@return Returns true if either zero length or null.*/
    static boolean isNullOrZeroLength(String para) //this means the string passed should be niether null nor 0
    {
    if (para != null)
    {
    if (para.length() > 0)
    return false;
    }
    return true;
    }
    //
    // static void main1(String[] jhdf) //to test with parameters
    // {
    // try
    // {
    // ConnectionPool connectionPool =
    // getPool(
    // "jdbc:odbc:leadserver",
    // "leadserver",
    // "leadserver",
    // "sun.jdbc.odbc.JdbcOdbcDriver",
    // 1,
    // 5,
    // 1);
    // /*System.out.println(" URL=url,  user=user,  password=pswd, dbDriver=dbDr, maxConns=4, timeOut=2, initConn=1 ");
    //
    //
    // connectionPool.setURL("url");
    // System.out.println("url set");
    // connectionPool.setUser("user");
    // System.out.println("user set");
    // connectionPool.setPassword("pswd");
    // System.out.println("password set");
    // connectionPool.setMaxConns(4);
    // System.out.println("time out set");
    // connectionPool.setTimeOut(2);
    // System.out.println("initial set");
    // connectionPool.setInitConn(1);
    // System.out.println("DBdriver set");
    // connectionPool.setDBDriver("dbDr");*/
    // connectionPool.printValues();
    //
    // connectionPool.printValues();
    // ResultSet rset = null;
    // Connection con = connectionPool.getConnection();
    // Statement stmt = con.createStatement();
    // rset =
    // stmt.executeQuery("select count(*) as cnt from HLLeadMaster");
    // rset.next();
    // int rows = rset.getInt("cnt");
    // System.out.println("cnt is ---- " + rows);
    //
    // System.out.println("All's clear ");
    // }
    // catch (Exception e)
    // {
    // System.out.println(e);
    // }
    // }
    /** Error message */
    private String message = "";
    /**
     * Get message, if any.
     * @return Returns recent message 
     */
    public String getMessage()
    {
    return message;
    } // private boolean isAcceptable(String userId)
    // {
    // userId = userId.toLowerCase();
    // if (userId.indexOf("demo") >= 0)
    // return true;
    // else
    // {
    // message =
    // "This is a demo version, userId should start with 'demo', you need to get a licensed copy for full featured version. \nPlease contact http://www.Infragistics.com to get the license";
    // System.out.println("Error:" + message);
    // return false;
    // }
    // } // static void main(String[] para) //to test WITHOUT parameters
    // {
    // try
    // {
    // // ConnectionPool.setFilePath("C:/java/jswdk-1.0.1/leadserver/WEB-INF/jsp/beans/com/ifg/utils/");
    // ConnectionPool.setFilePath(para[0]);
    // ConnectionPool connectionPool = getPool();
    // /* System.out.println(" URL=url,  user=user,  password=pswd, dbDriver=dbDr, maxConns=4, timeOut=2, initConn=1 ");
    // connectionPool.setURL("url");
    // System.out.println("url set");
    // connectionPool.setUser("user");
    // System.out.println("user set");
    // connectionPool.setPassword("pswd");
    // System.out.println("password set");
    // connectionPool.setMaxConns(4);
    // System.out.println("time out set");
    // connectionPool.setTimeOut(2);
    // System.out.println("initial set");
    // connectionPool.setInitConn(1);
    // System.out.println("DBdriver set");
    // connectionPool.setDBDriver("dbDr");*/
    // connectionPool.printValues();
    // ResultSet rset = null;
    // Connection con = connectionPool.getConnection();
    // Statement stmt = con.createStatement();
    // rset =
    // stmt.executeQuery("select count(*) as cnt from HLLeadMaster");
    // rset.next();
    // int rows = rset.getInt("cnt");
    // System.out.println(
    // "cnt--------------------------------------- " + rows);
    //
    // System.out.println("All's clear ");
    // }
    // catch (Exception e)
    // {
    // System.out.println(e);
    // }
    // }
    }
      

  5.   

    使用:
        Statement stm = null;
        ConnectionPool pool;
        try {
          pool = ConnectionPool.getPool("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=",
    "leadserver",
    "leadserver",
    "com.microsoft.jdbc.sqlserver.SQLServerDriver",
    1,
    5,
    1);
          Connection conn = pool.getConnection();
          stm = conn.createStatement();
          String sql = "…………";
          stm.executeUpdate(sql);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
      

  6.   

    Jakarta-Commons DBCP 
    Jakarta-Commons Collections 
    Jakarta-Commons Pool 只要配置datasource就行了
      

  7.   

    开源的支持使用:apache项目的
    商业的....
      

  8.   

    给我发一份:-)
    [email protected]
      

  9.   

    累就一个字
    CSDN该改版了
    这样看着好累
      

  10.   

    我也要一个 谢谢! 小弟也急用 
    [email protected]