日期:2014-05-16 浏览次数:20475 次
package com.wangjia.tools; import java.io.Serializable; import java.sql.*; import java.util.*; /** * 数据库连接池的简单实现 * @author wangjia * @version 1.0 *@serial 2301410997974776106L */ public class DbConn implements Serializable{ /** * */ private static final long serialVersionUID = 2301410997974776106L; private static List<Connection> connList=new ArrayList<Connection>(); //private static String driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";//sql2000 private static String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";//sql2005 private static String url="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Forum"; private static String userName="sa"; private static String password="sa"; private static int maxConn=20; private static int minConn=5; private static int usedConn=0; private static DbConn dbconn=null; // private static int flag=1; /** * 设置数据库连接的驱动 * @param driver 数据库连接的驱动<br/>例如:"com.microsoft.sqlserver.jdbc.SQLServerDriver" */ public static void setDriver(String driver) { DbConn.driver = driver; } /** * 设置数据库连接池的最小数量 * @param maxConn 数据库连接池的最小数量 */ public static void setMaxConn(int maxConn) { DbConn.maxConn = maxConn; } /** * 设置数据库连接池的最大数量 * @param minConn 数据库连接池的最大数量 */ public static void setMinConn(int minConn) { DbConn.minConn = minConn; } /** * 设置数据库连接的URL * @param url 数据库连接的URL,包括数据库的名称<br/>例如: "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=master" */ public static void setUrl(String url) { DbConn.url = url; } private DbConn() throws MyException{ try{ Class.forName(driver); for(int i=0;i<minConn;i++){ connList.add(DriverManager.getConnection(url,userName.toString(),password.toString())); } }catch(ClassNotFoundException e){ throw new MyException("请设置正确的数据库连接驱动!\nusing: DbConn.setDriver(String driver)"); }catch(SQLException e){ throw new MyException("请设置正确的数据库连接URL以及用于连接的用户名和密码!\n" + "using: DbConn.setUrl(String url),DbConn.setUserName(String userName),DbConn.setPassword(String password)"); } } /** * 用于得到DbConn对象 * @return 返回一个DbConn对像 */ public static Connection getConn() throws MyException{ // flag++; if(dbconn==null)dbconn=new DbConn(); // System.out.println("falg="+flag); // System.out.println("usedConn="+usedConn); if(connList.size()==0){ throw new MyException("没有正确的设置相关信息,以至连接池未初始化"); } if(usedConn==maxConn){ Thread thread=new Thread(new Runnable(){ @SuppressWarnings("static-access") public void run() { if(usedConn<maxConn){ try { try { Thread.currentThread().sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } getConn(); } catch (MyException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); thread.start(); } if(usedConn>=minConn&&usedConn<maxConn){ try { connList.add(DriverManager.getConnection(url,userName.toString(),password.toString())); } catch (SQLException e) { } return connList.get(usedConn++); } if(usedConn<5){ return connList.get(usedConn++); } return null; } public static void close(){ try { if(usedConn>5) connList.get(--usedConn).cl