`

Oracle连接池

阅读更多

Oracle连接池

 

public class ConnectionPool {
  private Vector pool;
  private String url;
  private String username;
  private String password;
  private String driverClassName;

  /***
   * 连接池的大小,也就是连接池中有多少个数据库连接
   */
  private int poolsize = 1;

  private static ConnectionPool instance = null;

  private ConnectionPool(){
    init();
  }

  private void init() {
    pool = new Vector(poolsize);
//    readConfig();
    addConnection();
  }

  /***
   * 返回连接到连接池中
   */

  public synchronized void release(Connection conn){
    pool.add(conn);
  }

  /***
   * 返回连接池中的一个对象
   */
  public static ConnectionPool getInstance(){
    if(instance == null){
      instance = new ConnectionPool();
    }
    return instance;
  }

  public synchronized Connection getConnection(){
    if(pool.size() > 0){
      Connection conn = (Connection) pool.get(0);
      pool.remove(conn);
      return conn;
    }else{
      return null;
    }
  }

//  private void readConfig() {
//    try{
//      String path = System.getProperty("user.dir"+"\\dbpool.properties");
//      FileInputStream is = new FileInputStream(path);
//      Properties props = new Properties();
//      props.load(is);
//      this.driverClassName = props.getProperty("driverClassName");
//      this.username = props.getProperty("username");
//      this.password = props.getProperty("password");
//      this.url = props.getProperty("url");
//      this.poolsize = Integer.parseInt(props.getProperty("poolsize"));
//      this.driverClassName="oracle.jdbc.driver.OracleDriver";
//      this.username="username";
//      this.password="abc";
//      this.url="jdbc:oracle:thin:@10.65.64.40:1522:orcl";
//      this.poolsize=10;
//
//    }catch(Exception e){
//      e.printStackTrace();
//      System.out.println("读取属性文件出错!");
//    }
//  }
  /***
   *
   */

  private void addConnection() {
    Connection conn = null;
    for(int i=0; i<10; i++){
      try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        conn = java.sql.DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "username", "abc");
        pool.add(conn);
      } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
      }
      catch (SQLException ex1) {
        ex1.printStackTrace();
      }
    }
  }

  /***
   * 关闭连接池中的连接
   */
  public synchronized void closePool(){
    for(int i=0; i<pool.size(); i++){
      try {
        ( (Connection) pool.get(i)).close();
      }
      catch (SQLException ex) {
        ex.printStackTrace();
      }
      pool.remove(i);
    }
  }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics