⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbconnectionmanager.java

📁 利用Java写的数据库连接池代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package bean;

 import java.io.*;
 import java.sql.*;
 import java.util.*;
 import java.util.Date;
/**
 * <p>Title: CSMIS</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author YIDONG(一冬)
 * @version 1.0
 */


 /**
 * 管理类DBConnectionManager支持对一个或多个由属性文件定义的数据库连接
 * 池的访问.客户程序可以调用getInstance()方法访问本类的唯一实例.
 */
 public class DBConnectionManager {
 static private DBConnectionManager instance; // 唯一实例
 static private int clients;
 //----------------test---------------//
 static private int connectCount = 0;
 public synchronized void addConnect()
 {
   connectCount ++;
   log("add connectCount=" + connectCount);
 }
 public synchronized void removeConnect()
 {
   connectCount --;
   log("remove connectCount=" + connectCount);
 }
 //----------------test---------------//

 private Vector drivers = new Vector();
 private PrintWriter log;
 private Hashtable pools = new Hashtable();

 /**
 * 返回唯一实例.如果是第一次调用此方法,则创建实例
 *
 * @return DBConnectionManager 唯一实例
 */
 static synchronized public DBConnectionManager getInstance() {
 if (instance == null) {
 instance = new DBConnectionManager();
 }
 clients++;
 return instance;
 }

 /**
 * 建构函数私有以防止其它对象创建本类实例
 */
 private DBConnectionManager() {
 init();
 }

 static synchronized public int getClients() {
 return clients;
 }
public synchronized int getCheckedOut(String name)
{
 DBConnectionPool pool = (DBConnectionPool) pools.get(name);
 if (pool != null) {
 return pool.getCheckedOut();
 }
return 0;
}

synchronized public int getfreeconn(String name)
{
 DBConnectionPool pool = (DBConnectionPool) pools.get(name);
 if (pool != null) {
 return pool.getfreeconn();
 }
return 0;
}

synchronized public long getmaxLiveTime(String name)
{
 DBConnectionPool pool = (DBConnectionPool) pools.get(name);
 if (pool != null) {
 return pool.maxLiveTime;
 }
return 0;
}



 /**
 * 将连接对象返回给由名字指定的连接池
 *
 * @param name 在属性文件中定义的连接池名字
 * @param con 连接对象
 */
 public void freeConnection(String name, JDCConnection con,String classname) {
   DBConnectionPool pool = null;
   synchronized (this){
         pool = (DBConnectionPool) pools.get(name);
   }
         if (pool != null)
         {
                try
                {
                        con.setAutoCommit(true);
                        pool.freeConnection(con,classname);
                }
                catch(Exception e)
                {
                }
         }
 }
 public void freeConnection(String name, JDCConnection con) {
    DBConnectionPool pool = null;
    synchronized (this){
          pool = (DBConnectionPool) pools.get(name);
    }
          if (pool != null)
          {
                 try
                 {
                         con.setAutoCommit(true);
                         pool.freeConnection(con);
                 }
                 catch(Exception e)
                 {
                 }
          }
 }
 /**
 * 获得一个可用的(空闲的)连接.如果没有可用连接,且已有连接数小于最大连接数
 * 限制,则创建并返回新连接
 *
 * @param name 在属性文件中定义的连接池名字
 * @return Connection 可用连接或null
 */
 public JDCConnection getConnection(String name,String classname) {
   DBConnectionPool pool = null;
   synchronized (this){
     pool = (DBConnectionPool) pools.get(name);
   }

 if (pool != null) {
   log("getConnection connectCount=" + connectCount);
 return pool.getConnection(classname);
 }
 return null;
 }
 public JDCConnection getConnection(String name) {
    DBConnectionPool pool = null;
    synchronized (this){
      pool = (DBConnectionPool) pools.get(name);
    }

  if (pool != null) {
    log("getConnection connectCount=" + connectCount);
  return pool.getConnection();
  }
  return null;
 }
 /**
 * 获得一个可用连接.若没有可用连接,且已有连接数小于最大连接数限制,
 * 则创建并返回新连接.否则,在指定的时间内等待其它线程释放连接.
 *
 * @param name 连接池名字
 * @param time 以毫秒计的等待时间
 * @return Connection 可用连接或null
 */
 public JDCConnection getConnection(String name, long time,String classname) {
   DBConnectionPool pool = null;
//   synchronized (this){
     pool = (DBConnectionPool) pools.get(name);
//   }
 if (pool != null) {
 return pool.getConnection(time,classname);
 }
 return null;
 }
 public JDCConnection getConnection(String name, long time) {
    DBConnectionPool pool = null;
//   synchronized (this){
      pool = (DBConnectionPool) pools.get(name);
//   }
  if (pool != null) {
  return pool.getConnection(time);
  }
  return null;
 }


 /**
 * 关闭所有连接,撤销驱动程序的注册
 */
 public synchronized void release() {
 // 等待直到最后一个客户程序调用
 if (--clients != 0) {
 return;
 }



 Enumeration allPools = pools.elements();
 while (allPools.hasMoreElements()) {
 DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
 pool.release();
 }
 Enumeration allDrivers = drivers.elements();
 while (allDrivers.hasMoreElements()) {
 Driver driver = (Driver) allDrivers.nextElement();
 try {
 DriverManager.deregisterDriver(driver);
 log(":::撤销JDBC驱动程序 " + driver.getClass().getName()+"的注册");
 }
 catch (SQLException e) {
 log(e, ":::无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName());
 }
 }
 }

 /**
 * 根据指定属性创建连接池实例.
 *
 * @param props 连接池属性
 */
 private void createPools(Properties props) {
 Enumeration propNames = props.propertyNames();
 while (propNames.hasMoreElements()) {
 String name = (String) propNames.nextElement();
 if (name.endsWith(".url")) {
 String poolName = name.substring(0, name.lastIndexOf("."));
 String url = props.getProperty(poolName + ".url");
 if (url == null) {
 log(":::没有为连接池" + poolName + "指定URL");
 continue;
 }
 String user = props.getProperty(poolName + ".user");
 String password = props.getProperty(poolName + ".password");
 String maxconn = props.getProperty(poolName + ".maxconn", "0");
 String maxlivetime = props.getProperty(poolName + ".maxlivetime", "10000");
 int max;
 try {
 max = Integer.valueOf(maxconn).intValue();
 }
 catch (NumberFormatException e) {
 log(":::错误的最大连接数限制: " + maxconn + " .连接池: " + poolName);
 max = 0;
 }
 long maxtime;
 try {
 maxtime = Long.valueOf(maxlivetime).intValue();
 }
 catch (NumberFormatException e) {
 log(":::错误的最大连接数限制: " + maxconn + " .连接池: " + poolName);
 maxtime = 0;
 }

 DBConnectionPool pool =
 new DBConnectionPool(poolName, url, user, password, max ,maxtime);
 pools.put(poolName, pool);
 log(":::成功创建连接池" + poolName);
 }
 }
 }

 /**
 * 读取属性完成初始化
 */
 private void init() {
 InputStream is = getClass().getResourceAsStream("/db.properties");
 Properties dbProps = new Properties();
 try {
 dbProps.load(is);
 }
 catch (Exception e) {
 System.err.println("不能读取属性文件. " +
 "请确保db.properties在CLASSPATH指定的路径中");
 return;
 }
 String logFile = dbProps.getProperty("logfile", "DBConnectionManager.log");
 try {
 log = new PrintWriter(new FileWriter(logFile, true), true);
 }
 catch (IOException e) {
// System.err.println("无法打开日志文件: " + logFile);
 log = new PrintWriter(System.err);
 System.out.println("DBConnectionManager error:无法打开日志文件: " + logFile);
 }
 loadDrivers(dbProps);
 createPools(dbProps);
 }

 /**
 * 装载和注册所有JDBC驱动程序
 *
 * @param props 属性
 */
 private void loadDrivers(Properties props) {
 String driverClasses = props.getProperty("drivers");
 StringTokenizer st = new StringTokenizer(driverClasses);
 while (st.hasMoreElements()) {
 String driverClassName = st.nextToken().trim();
 try {
 Driver driver = (Driver)
 Class.forName(driverClassName).newInstance();
 DriverManager.registerDriver(driver);
 drivers.addElement(driver);
 log(":::成功注册JDBC驱动程序" + driverClassName);
 }
 catch (Exception e) {
 log(":::无法注册JDBC驱动程序: " +
 driverClassName + ", 错误: " + e);
 }
 }
 }

 /**
 * 将文本信息写入日志文件
 */

private void logerr(String msg) {
  try{
    PrintWriter log1 = new PrintWriter(new FileWriter(
        "/dberrzzy.txt", true), true);
    log1.println(new Date() + ": " + toGBString(msg));
  }catch(Exception ee){}
}

 private void log(String msg) {
 log.println(new Date() + ": " + toGBString(msg));
 //System.out.println(new Date() + ": " + toGBString(msg));
 }

 /**
 * 将文本信息与异常写入日志文件
 */
 private void log(Throwable e, String msg) {
 log.println(new Date() + ": " + toGBString(msg));
 e.printStackTrace(log);
 }

 /**
 * 将字符转换为GB2312
 */
private String toGBString(String str)
{//将字符转换为GB2312
        String returnstr="";
        try
        {
                returnstr=new String((str.getBytes("GB2312")));

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -