这是在网上浏览的时候发现不知哪位写的数据库连接池,我在这里只把
getConnection和freeConnection两个方法摘出来,一个是用来对外提供连接的,一个是用来回收连接的。大家给看看,这个数据库连接池的写法怎么这个样子,能管用么?
public final class DBPool 
{
    private static ArrayList<Connection> freeConnection=new ArrayList<Connection>();
    
    /** Creates a new instance of DBPool */
    private DBPool() 
    {
    }
    
    static
    {
        try
        {
            for(int i=0;i<=9;i++)
            {
                Class.forName("org.gjt.mm.mysql.Driver");
                Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?user=root&password=");
                freeConnection.add(con);
            }
            
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    
    public static Connection getConnection()
    {
        Connection con=null;
        if(freeConnection.size()>0)
        {
            con=freeConnection.remove(0);
        }
        return con;        
    }
    
    public static boolean freeConnection(Connection con)
    {
        return freeConnection.add(con);
    }
}

解决方案 »

  1.   

    JDBC 4.0 specification is the best article how to write pooledConnection
    you can just follow the guideline......
    then complete the relevant API invoked, you also can using JNDI for pooledConnection
      

  2.   

    可以考虑用第三方的,如dbcp。proxool等
      

  3.   

    getConnection()方法有可能返回一个空连接,这就需要应用程序来处理了,封装不彻底。如果size() == 0,可以考虑增加连接,然后返回增加的连接;同时如果某些连接长时间不用,可以考虑关闭,只保留最少连接数。