日期:2014-05-16 浏览次数:20476 次
package test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Date; import java.util.Vector; public class ConnectionPool { private final Vector pools = new Vector(); private int clients; private final int maxClients=25; /** * 获取数据库连接 如果当前池中有可用连接,则将池中最后一个返回;若没有,则创建一个新的返回 */ public synchronized java.sql.Connection getConnection() { java.sql.Connection con = null; if (pools.size() > 0) { // Pick the first Connection in the Vector // to get round-robin usage con = (java.sql.Connection) pools.firstElement(); pools.removeElementAt(0); try { if (con.isClosed()) { System.out .println("Removed bad connection from connection pool"); // Try again recursively con = getConnection(); } } catch (SQLException e) { System.out .println("Removed bad connection from connection pool"); // Try again recursively con = getConnection(); } } else if (maxClients == 0 || clients < maxClients) { con = createConnection(); } if (con != null) { clients++; } return con; } /* * 当对一个连接的请求不能被满足时,等待,直到pool中有空闲Connection */ public synchronized java.sql.Connection getConnection(long timeout) { long startTime = new Date().getTime(); java.sql.Connection con; while ((con = getConnection()) == null) { try { wait(timeout); } catch (InterruptedException e) { } if ((new Date().getTime() - startTime) >= timeout) { // Timeout has expired return null; } } return con; } /* * 生成一个数据库连接conn */ public static Connection createConnection() { Connection conn = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); String url = "jdbc:mysql://localhost:3306/microerp"; String user = "root"; String password = ""; conn = DriverManager.getConnection(url, user, password); } catch (InstantiationException e) { // TODO自动生成 catch 块 e.printStackTrace(); } catch (IllegalAccessException e) { // TODO自动生成 catch 块 e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO自动生成 catch 块 e.printStackTrace(); } catch (SQLException e) { // TODO自动生成 catch 块 e.printStackTrace(); } return conn; } /** * 将使用完毕的数据库连接放回池中 若池中连接已经超过阈值,则关闭该连接;否则放回池中下次再使用 */ public synchronized void releaseConnection(Connection conn) { if (pools.size() >= maxClients) try { conn.close(); } catch (SQLException e) { // TODO自动生成 catch 块 e.printStackTrace(); } else { pools.add(conn); clients--; notify(); } } public synchronized void clear(){