DBConnectionManager

package zpxx;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;

//建立DBConnectionManager
public class DBConnectionManager
{
 static private DBConnectionManager instance;
 static private int clients;

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

 //返回唯一的实列
 static synchronized public DBConnectionManager getInstance()
 {
  if(instance==null)
  {
   instance=new DBConnectionManager();
  }
  clients++;
  return instance;
 }

 //构造函数!
 private DBConnectionManager()
 {
  init();
 }
 //结束构造函数
 //释放一个连接
 public void freeConnection(String name,Connection con)
 {
  DBConnectionPool pool=(DBConnectionPool)pools.get(name);
  if(pool!=null)
  {
   pool.freeConnection(con);
  }
 } 
 //结束释放一个连接

 //取得一个连接
 public Connection getConnection(String name)
 {
  DBConnectionPool pool=(DBConnectionPool)pools.get(name);
  if(pool!=null)
  {
   return pool.getConnection();
  }
  return null;
 }

 public Connection getConnection(String name,String customer)
 {
  DBConnectionPool pool=(DBConnectionPool)pools.get(name);
  if(pool!=null)
  {
   return pool.getConnection(customer);
  }
  return null;
 }

 public Connection getConnection(String name,long time)
 {
  DBConnectionPool pool=(DBConnectionPool)pools.get(name);
  if(pool!=null)
  {
   return pool.getConnection(time);
  }
  return null;
 }
 //结束getconnection
 //关闭所有连接
 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());
   }
  }
 }

 public synchronized void release(String customer)
 {
//  if(--clients!=0)
//   return;

  Enumeration allPools=pools.elements();
  while(allPools.hasMoreElements())
  {
   DBConnectionPool pool=(DBConnectionPool)allPools.nextElement();
   pool.release(customer);
  }
  Enumeration allDrivers=drivers.elements();
  while(allDrivers.hasMoreElements())
  {
   Driver driver=(Driver)allDrivers.nextElement();
   try
   {
    DriverManager.deregisterDriver(driver);
    log(customer+"撤消JDBC驱动程序"+driver.getClass().getName());
   }
   catch(SQLException e)
   {
    log(e,"无法撤消JDBC驱动程序的注册"+driver.getClass().getName());
   }
  }
 }
 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");
    int max;
    try
    {
     max=Integer.valueOf(maxconn).intValue();
    }
    catch(NumberFormatException e)
    {
     log("错误的最大连接数:"+maxconn+".连接池"+poolName);
     max=0;
    }
    DBConnectionPool pool=new DBConnectionPool(poolName,url,user,password,max);
    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);
  }
  loadDriver(dbProps);
  createPools(dbProps);
 }

 private void loadDriver(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("成功注册驱动程序"+driverClassName);
   }
   catch(Exception e)
   {
    log("无法注册驱动程序:"+driverClassName+",错误"+e);
   }
  }
 }

 private void log(String msg)
 {
  log.println(new Date()+":"+msg);
 }
 private void log(Throwable e,String msg)
 {
  log.println(new Date()+":"+msg);
  e.printStackTrace(log);
 }
 class DBConnectionPool
 {
  private int checkOut;
  private Vector freeConnections=new Vector();
  private int maxconn;
  private String name;
  private String password;
  private String URL;
  private String user;

  public DBConnectionPool(String name,String URL,String user,String password,int maxconn)
  {
   this.name=name;
   this.URL=URL;
   this.password=password;
   this.user=user;
   this.maxconn=maxconn;
  }
  public synchronized void freeConnection(Connection con)
  {
   freeConnections.addElement(con);
   checkOut--;
   notifyAll();
  }
  public synchronized Connection getConnection()
  {
   Connection con=null;
   if(freeConnections.size()>0)
   {
    con=(Connection)freeConnections.firstElement();
    freeConnections.removeElementAt(0);
    try
    {
     if(con.isClosed())
     {
      log("从连接池"+name+"删除一个连接");
      con=getConnection();
     }
    }
    catch(SQLException e)
    {
     log("从连接池"+name+"删除一个连接");
     con=getConnection();
    }
   }
   else if(maxconn==0||checkOut<maxconn)
   {
    con=newConnection();
   }
   if(con!=null)
   {
    checkOut++;
   }
   return con;
  }

  public synchronized Connection getConnection(String customer)
  {
   Connection con=null;
   if(freeConnections.size()>0)
   {
    con=(Connection)freeConnections.firstElement();
    freeConnections.removeElementAt(0);
    try
    {
     if(con.isClosed())
     {
      log("从连接池"+name+"删除一个连接");
      con=getConnection();
     }
    }
    catch(SQLException e)
    {
     log("从连接池"+name+"删除一个连接");
     con=getConnection();
    }
   }
   else if(maxconn==0||checkOut<maxconn)
   {
    con=newConnection(customer);
   }
   if(con!=null)
   {
    checkOut++;
   }
   return con;
  }

  public synchronized Connection getConnection(long timeout)
  {
   long startTime=new Date().getTime();
   Connection con;
   while((con=getConnection())==null)
   {
    try
    {
     wait(timeout);
    }
    catch(InterruptedException e)
    {}
    if((new Date().getTime()-startTime)>=timeout)
    {
     return null;
    }
   }
   return con;
  }
  public void release()
  {
   Enumeration allConnections=freeConnections.elements();
   while(allConnections.hasMoreElements())
   {
    Connection con=(Connection)allConnections.nextElement();
    try
    {
     con.close();
     log("关闭连接池"+name+"中的连接");
    }
    catch(SQLException e)
    {
     log(e,"无法关闭连接池"+name+"中的连接");
    }
   }
   freeConnections.removeAllElements();
  }
  public void release(String customer)
  {
   Enumeration allConnections=freeConnections.elements();
   while(allConnections.hasMoreElements())
   {
    Connection con=(Connection)allConnections.nextElement();
    try
    {
     con.close();
     log(customer+"关闭连接池"+name+"中的连接");
    }
    catch(SQLException e)
    {
     log(e,"无法关闭连接池"+name+"中的连接");
    }
   }
   freeConnections.removeAllElements();
  }
  private Connection newConnection()
  {
   Connection con=null;
   try
   {
    con=DriverManager.getConnection(URL,user,password);
    log("连接池"+name+"创建一个新的连接");
   }
   catch(SQLException e)
   {
    log(e,"无法创建下列URL的连接"+URL);
    return null;
   }
   return con;
  }

  private Connection newConnection(String customer)
  {
   Connection con=null;
   try
   {
    con=DriverManager.getConnection(URL,user,password);
    log(customer+"从连接池"+name+"创建一个新的连接");
   }
   catch(SQLException e)
   {
    log(e,"无法创建下列URL的连接"+URL);
    return null;
   }
   return con;
  }
 }
}

package com.hexiang.utils.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.apache.log4j.Logger; public class DBConnection { /** * 获得与数据库的连接 * * @param path * @return Connection */ public static Connection getConn(String classDriver, String url, String user, String pwd) { try { Class.forName(classDriver); return DriverManager.getConnection(url, user, pwd); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } public static Connection getConn(DataSource dataSource) { try { return dataSource.getConnection(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } public static Connection getConn(String jndiName) { try { Context ctx; ctx = new InitialContext(); DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/" + jndiName); return dataSource.getConnection(); } catch (NamingException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } public static Connection getConn(Properties properties) { try { String driver = properties.getProperty("jdbc.driverClassName"); String url = properties.getProperty("jdbc.url"); String user = properties.getProperty("jdbc.username"); String password = properties.getProperty("jdbc.password"); Class.forName(driver); return DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } /** * oracle连接 * * @param path * @return Connection */ public static Connection getOracleConn(String
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.core; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class ConnDB { public Connection conn = null; public Statement stmt = null; public ResultSet rs = null; private static String propFileName = "/com/connDB.properties"; private static Properties prop = new Properties(); private static String dbClassName = "com.mysql.jdbc.Driver"; private static String dbUrl = "jdbc:mysql://127.0.0.1:3306/db_librarysys?user=root&password=aaaaaa&useUnicode=true"; public ConnDB() { try { InputStream in = this.getClass().getResourceAsStream(propFileName); prop.load(in); dbClassName = prop.getProperty("DB_CLASS_NAME"); dbUrl = prop.getProperty("DB_URL", dbUrl); } catch (Exception var2) { var2.printStackTrace(); } } public static Connection getConnection() { Connection conn = null; try { Class.forName(dbClassName).newInstance(); conn = DriverManager.getConnection(dbUrl); } catch (Exception var2) { var2.printStackTrace(); System.out.println("wgh:" + dbUrl); } if (conn == null) { System.err.println("警告: DbConnectionManager.getConnection() 获得数据库链接失败.\r\n\r\n链接类型:" + dbClassName + "\r\n链接位置1:" + dbUrl); } return conn; } public ResultSet executeQuery(String sql) { try { this.conn = getConnection(); this.stmt = this.conn.createStatement(1004, 1007); this.rs = this.stmt.executeQuery(sql); } catch (SQLException var3) { System.err.println(var3.getMessage()); } return this.rs; } public int executeUpdate(String sql) { boolean var2 = false; int result; try { this.conn = getConnection(); this.stmt = this.conn.createStatement(1004, 1007); result = this.stmt.executeUpdate(sql); } catch (SQLException var4) { result = 0; } return result; } public void close() { try { if (this.rs != null) { this.rs.close(); } if (this.stmt != null) { this.stmt.close(); } if (this.conn != null) { this.conn.close(); } } catch (Exception var2) { var2.printStackTrace(System.err); } } }
最新发布
05-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值