Java jdbc数据库连接池总结

来源:互联网 发布:足球赛程编排软件 编辑:程序博客网 时间:2024/05/22 12:41

转自:http://blog.csdn.net/wangtao7752/article/details/8350743



1. 引言

  近年来,随着Internet/Intranet建网技术的飞速发展和在世界范围内的迅速普及,计算机应用程序已从传统的桌面应用转到Web应用。基于B/S(Browser/Server)架构的3层开发模式逐渐取代C/S(Client/Server)架构的开发模式,成为开发企业级应用和电子商务普遍采用的技术。在Web应用开发的早期,主要使用的技术是CGIASPPHP等。之后,Sun公司推出了基于Java语言的Servlet+Jsp+JavaBean技术。相比传统的开发技术,它具有跨平台﹑安全﹑有效﹑可移植等特性,这使其更便于使用和开发。

        Java应用程序访问数据库的基本原理

        在Java语言中,JDBC(Java DataBase Connection)是应用程序与数据库沟通的桥梁,即Java语言通过JDBC技术访问数据库。JDBC是一种“开放”的方案,它为数据库应用开发人员﹑数据库前台工具开发人员提供了一种标准的应用程序设计接口,使开发人员可以用纯Java语言编写完整的数据库应用程序。JDBC提供两种API,分别是面向开发人员的API和面向底层的JDBC驱动程序API,底层主要通过直接的JDBC驱动和JDBC-ODBC桥驱动实现与数据库的连接。

一般来说,Java应用程序访问数据库的过程(如图1所示)是:
  ①装载数据库驱动程序;
  ②通过JDBC建立数据库连接;
  ③访问数据库,执行SQL语句;
  ④断开数据库连接。

 

                                                                                                                                                                           

                                                                图1 Java数据库访问机制

 

JDBC作为一种数据库访问技术,具有简单易用的优点。但使用这种模式进行Web应用程序开发,存在很多问题:首先,每一次Web请求都要建立一次数据库连接。建立连接是一个费时的活动,每次都得花费0.05s~1s的时间,而且系统还要分配内存资源。这个时间对于一次或几次数据库操作,或许感觉不出系统有多大的开销。可是对于现在的Web应用,尤其是大型电子商务网站,同时有几百人甚至几千人在线是很正常的事。在这种情况下,频繁的进行数据库连接操作势必占用很多的系统资源,网站的响应速度必定下降,严重的甚至会造成服务器的崩溃。不是危言耸听,这就是制约某些电子商务网站发展的技术瓶颈问题。其次,对于每一次数据库连接,使用完后都得断开。否则,如果程序出现异常而未能关闭,将会导致数据库系统中的内存泄漏,最终将不得不重启数据库。还有,这种开发不能控制被创建的连接对象数,系统资源会被毫无顾及的分配出去,如连接过多,也可能导致内存泄漏,服务器崩溃。

 
 数据库连接池(connection pool)的工作原理
1、基本概念及原理
        由上面的分析可以看出,问题的根源就在于对数据库连接资源的低效管理。我们知道, 对于共享资源,有一个很著名的设计模式:资源池(Resource Pool)。该模式正是为了解决资源的频繁分配﹑释放所造成的问题。为解决上述问题,可以采用数据库连接池技术。数据库连接池的基本思想就是为数据库连接建立一个“缓冲池”。预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕之后再放回去。我们可以通过设定连接池最大连接数来防止系统无尽的与数据库连接。更为重要的是我们可以通过连接池的管理机制监视数据库的连接的数量﹑使用情况,为系统开发﹑测试及性能调整提供依据。连接池的基本工作原理见下图2。

 

                                                        图2 连接池的基本工作原理

2、服务器自带的连接池

  JDBC的API中没有提供连接池的方法。一些大型的WEB应用服务器如BEA的WebLogic和IBM的WebSphere等提供了连接池的机制,但是必须有其第三方的专用类方法支持连接池的用法。
  连接池关键问题分析
  1、并发问题
  为了使连接管理服务具有最大的通用性,必须考虑多线程环境,即并发问题。这个问题相对比较好解决,因为Java语言自身提供了对并发管理的支持,使用synchronized关键字即可确保线程是同步的。使用方法为直接在类方法前面加上synchronized关键字,如:public synchronized Connection getConnection()
  2、多数据库服务器和多用户
  对于大型的企业级应用,常常需要同时连接不同的数据库(如连接OracleSybase)。如何连接不同的数据库呢?我们采用的策略是:设计一个符合单例模式的连接池管理类,在连接池管理类的唯一实例被创建时读取一个资源文件,其中资源文件中存放着多个数据库的url地址(<poolName.url>)﹑用户名(<poolName.user>)﹑密码(<poolName.password>)等信息。如tx.url=192.168.1.123:5000/tx_it,tx.user=cyl,tx.password=123456。根据资源文件提供的信息,创建多个连接池类的实例,每一个实例都是一个特定数据库的连接池。连接池管理类实例为每个连接池实例取一个名字,通过不同的名字来管理不同的连接池。
  对于同一个数据库有多个用户使用不同的名称和密码访问的情况,也可以通过资源文件处理,即在资源文件中设置多个具有相同url地址,但具有不同用户名和密码的数据库连接信息。
  3、事务处理
  我们知道,事务具有原子性,此时要求对数据库的操作符合“ALL-ALL-NOTHING”原则,即对于一组SQL语句要么全做,要么全不做。在Java语言中,Connection类本身提供了对事务的支持,可以通过设置Connection的AutoCommit属性为false,然后显式的调用commit或rollback方法来实现。但要高效的进行Connection复用,就必须提供相应的事务支持机制。可采用每一个事务独占一个连接来实现,这种方法可以大大降低事务管理的复杂性。
  4、连接池的分配与释放
  连接池的分配与释放,对系统的性能有很大的影响。合理的分配与释放,可以提高连接的复用度,从而降低建立新连接的开销,同时还可以加快用户的访问速度。
  对于连接的管理可使用空闲池。即把已经创建但尚未分配出去的连接按创建时间存放到一个空闲池中。每当用户请求一个连接时,系统首先检查空闲池内有没有空闲连接。如果有就把建立时间最长(通过容器的顺序存放实现)的那个连接分配给他(实际是先做连接是否有效的判断,如果可用就分配给用户,如不可用就把这个连接从空闲池删掉,重新检测空闲池是否还有连接);如果没有则检查当前所开连接池是否达到连接池所允许的最大连接数(maxConn),如果没有达到,就新建一个连接,如果已经达到,就等待一定的时间(timeout)。如果在等待的时间内有连接被释放出来就可以把这个连接分配给等待的用户,如果等待时间超过预定时间timeout,则返回空值(null)。系统对已经分配出去正在使用的连接只做计数,当使用完后再返还给空闲池。对于空闲连接的状态,可开辟专门的线程定时检测,这样会花费一定的系统开销,但可以保证较快的响应速度。也可采取不开辟专门线程,只是在分配前检测的方法。
  5、连接池的配置与维护
  连接池中到底应该放置多少连接,才能使系统的性能最佳?系统可采取设置最小连接数(minConn)和最大连接数(maxConn)来控制连接池中的连接。最小连接数是系统启动时连接池所创建的连接数。如果创建过多,则系统启动就慢,但创建后系统的响应速度会很快;如果创建过少,则系统启动的很快,响应起来却慢。这样,可以在开发时,设置较小的最小连接数,开发起来会快,而在系统实际使用时设置较大的,因为这样对访问客户来说速度会快些。最大连接数是连接池中允许连接的最大数目,具体设置多少,要看系统的访问量,可通过反复测试,找到最佳点。
  如何确保连接池中的最小连接数呢?有动态和静态两种策略。动态即每隔一定时间就对连接池进行检测,如果发现连接数量小于最小连接数,则补充相应数量的新连接,以保证连接池的正常运转。静态是发现空闲连接不够时再去检查。
连接池的实现
  1、连接池模型
  本文讨论的连接池包括一个连接池类(DBConnectionPool)和一个连接池管理类(DBConnetionPoolManager)和一个配置文件操作类(ParseDSConfig)。连接池类是对某一数据库所有连接的“缓冲池”,主要实现以下功能:①从连接池获取或创建可用连接;②使用完毕之后,把连接返还给连接池;③在系统关闭前,断开所有连接并释放连接占用的系统资源;④还能够处理无效连接(原来登记为可用的连接,由于某种原因不再可用,如超时,通讯问题),并能够限制连接池中的连接总数不低于某个预定值和不超过某个预定值。(5)当多数据库时,且数据库是动态增加的话,将会加到配置文件中。
  连接池管理类是连接池类的外覆类(wrapper),符合单例模式,即系统中只能有一个连接池管理类的实例。其主要用于对多个连接池对象的管理,具有以下功能:①装载并注册特定数据库的JDBC驱动程序;②根据属性文件给定的信息,创建连接池对象;③为方便管理多个连接池对象,为每一个连接池对象取一个名字,实现连接池名字与其实例之间的映射;④跟踪客户使用连接情况,以便需要是关闭连接释放资源。连接池管理类的引入主要是为了方便对多个连接池的使用和管理,如系统需要连接不同的数据库,或连接相同的数据库但由于安全性问题,需要不同的用户使用不同的名称和密码。
         2、连接池实现(经过本人改版,可以适用多数据库类型的应用以及一种数据库类型多个数据库且数据  库的数量可以动态增加的应用程序)
         1),DBConnectionPool.java   数据库连接池类
         2),DBConnectionManager .java   数据库管理类
         3),DSConfigBean .java                单个数据库连接信息Bean
         4),ParseDSConfig.java                操作多(这个'多'包括不同的数据库和同一种数据库有多个数据库)
                                                            数据 配置文件xml
         5),ds.config.xml                           数据库配置文件xml
         原代码如下: 
[java] view plaincopyprint?
  1.  DBConnectionPool.java     
  2.         ----------------------------------------------------------  
  3.       /** 
  4.  * 数据库连接池类 
  5.  */  
  6. import java.sql.Connection;  
  7. import java.sql.DriverManager;  
  8. import java.sql.SQLException;  
  9. import java.util.ArrayList;  
  10. import java.util.Iterator;  
  11. import java.util.Timer;  
  12. public class DBConnectionPool implements TimerListener {  
  13.  private Connection con=null;  
  14.  private int inUsed=0;    //使用的连接数  
  15.  private ArrayList freeConnections = new ArrayList();//容器,空闲连接  
  16.  private int minConn;     //最小连接数  
  17.  private int maxConn;     //最大连接  
  18.  private String name;     //连接池名字  
  19.  private String password; //密码  
  20.  private String url;      //数据库连接地址  
  21.  private String driver;   //驱动  
  22.  private String user;     //用户名  
  23.  public Timer timer;      //定时  
  24.  /** 
  25.   *  
  26.   */  
  27.  public DBConnectionPool() {  
  28.   // TODO Auto-generated constructor stub  
  29.  }  
  30.  /** 
  31.   * 创建连接池 
  32.   * @param driver 
  33.   * @param name 
  34.   * @param URL 
  35.   * @param user 
  36.   * @param password 
  37.   * @param maxConn 
  38.   */  
  39.  public DBConnectionPool(String name, String driver,String URL, String user, String password, int maxConn)  
  40.  {  
  41.   this.name=name;  
  42.   this.driver=driver;  
  43.   this.url=URL;  
  44.   this.user=user;  
  45.   this.password=password;  
  46.   this.maxConn=maxConn;  
  47.  }  
  48.  /** 
  49.   * 用完,释放连接 
  50.   * @param con 
  51.   */  
  52.  public synchronized void freeConnection(Connection con)   
  53.  {  
  54.   this.freeConnections.add(con);//添加到空闲连接的末尾  
  55.   this.inUsed--;  
  56.  }  
  57.  /** 
  58.   * timeout  根据timeout得到连接 
  59.   * @param timeout 
  60.   * @return 
  61.   */  
  62.  public synchronized Connection getConnection(long timeout)  
  63.  {  
  64.   Connection con=null;  
  65.   if(this.freeConnections.size()>0)  
  66.   {  
  67.    con=(Connection)this.freeConnections.get(0);  
  68.    if(con==null)con=getConnection(timeout); //继续获得连接  
  69.   }  
  70.   else  
  71.   {  
  72.    con=newConnection(); //新建连接  
  73.   }  
  74.   if(this.maxConn==0||this.maxConn<this.inUsed)  
  75.   {  
  76.    con=null;//达到最大连接数,暂时不能获得连接了。  
  77.   }  
  78.   if(con!=null)  
  79.   {  
  80.    this.inUsed++;  
  81.   }  
  82.   return con;  
  83.  }  
  84.  /** 
  85.   *  
  86.   * 从连接池里得到连接 
  87.   * @return 
  88.   */  
  89.  public synchronized Connection getConnection()  
  90.  {  
  91.   Connection con=null;  
  92.   if(this.freeConnections.size()>0)  
  93.   {  
  94.    con=(Connection)this.freeConnections.get(0);  
  95.    this.freeConnections.remove(0);//如果连接分配出去了,就从空闲连接里删除  
  96.    if(con==null)con=getConnection(); //继续获得连接  
  97.   }  
  98.   else  
  99.   {  
  100.    con=newConnection(); //新建连接  
  101.   }  
  102.   if(this.maxConn==0||this.maxConn<this.inUsed)  
  103.   {  
  104.    con=null;//等待 超过最大连接时  
  105.   }  
  106.   if(con!=null)  
  107.   {  
  108.    this.inUsed++;  
  109.    System.out.println("得到 "+this.name+" 的连接,现有"+inUsed+"个连接在使用!");  
  110.   }  
  111.   return con;  
  112.  }  
  113.  /** 
  114.   *释放全部连接 
  115.   * 
  116.   */  
  117.  public synchronized void release()  
  118.  {  
  119.   Iterator allConns=this.freeConnections.iterator();  
  120.   while(allConns.hasNext())  
  121.   {  
  122.    Connection con=(Connection)allConns.next();  
  123.    try  
  124.    {  
  125.     con.close();  
  126.    }  
  127.    catch(SQLException e)  
  128.    {  
  129.     e.printStackTrace();  
  130.    }  
  131.      
  132.   }  
  133.   this.freeConnections.clear();  
  134.      
  135.  }  
  136.  /** 
  137.   * 创建新连接 
  138.   * @return 
  139.   */  
  140.  private Connection newConnection()  
  141.  {  
  142.   try {  
  143.    Class.forName(driver);  
  144.    con=DriverManager.getConnection(url, user, password);  
  145.   } catch (ClassNotFoundException e) {  
  146.    // TODO Auto-generated catch block  
  147.    e.printStackTrace();  
  148.    System.out.println("sorry can't find db driver!");  
  149.   } catch (SQLException e1) {  
  150.    // TODO Auto-generated catch block  
  151.    e1.printStackTrace();  
  152.    System.out.println("sorry can't create Connection!");  
  153.   }  
  154.   return con;  
  155.     
  156.  }  
  157.  /** 
  158.   * 定时处理函数 
  159.   */  
  160.  public synchronized void TimerEvent()   
  161.  {  
  162.      //暂时还没有实现以后会加上的  
  163.  }  
  164.  /** 
  165.   * @param args 
  166.   */  
  167.  public static void main(String[] args) {  
  168.   // TODO Auto-generated method stub  
  169.  }  
  170.  /** 
  171.   * @return the driver 
  172.   */  
  173.  public String getDriver() {  
  174.   return driver;  
  175.  }  
  176.  /** 
  177.   * @param driver the driver to set 
  178.   */  
  179.  public void setDriver(String driver) {  
  180.   this.driver = driver;  
  181.  }  
  182.  /** 
  183.   * @return the maxConn 
  184.   */  
  185.  public int getMaxConn() {  
  186.   return maxConn;  
  187.  }  
  188.  /** 
  189.   * @param maxConn the maxConn to set 
  190.   */  
  191.  public void setMaxConn(int maxConn) {  
  192.   this.maxConn = maxConn;  
  193.  }  
  194.  /** 
  195.   * @return the minConn 
  196.   */  
  197.  public int getMinConn() {  
  198.   return minConn;  
  199.  }  
  200.  /** 
  201.   * @param minConn the minConn to set 
  202.   */  
  203.  public void setMinConn(int minConn) {  
  204.   this.minConn = minConn;  
  205.  }  
  206.  /** 
  207.   * @return the name 
  208.   */  
  209.  public String getName() {  
  210.   return name;  
  211.  }  
  212.  /** 
  213.   * @param name the name to set 
  214.   */  
  215.  public void setName(String name) {  
  216.   this.name = name;  
  217.  }  
  218.  /** 
  219.   * @return the password 
  220.   */  
  221.  public String getPassword() {  
  222.   return password;  
  223.  }  
  224.  /** 
  225.   * @param password the password to set 
  226.   */  
  227.  public void setPassword(String password) {  
  228.   this.password = password;  
  229.  }  
  230.  /** 
  231.   * @return the url 
  232.   */  
  233.  public String getUrl() {  
  234.   return url;  
  235.  }  
  236.  /** 
  237.   * @param url the url to set 
  238.   */  
  239.  public void setUrl(String url) {  
  240.   this.url = url;  
  241.  }  
  242.  /** 
  243.   * @return the user 
  244.   */  
  245.  public String getUser() {  
  246.   return user;  
  247.  }  
  248.  /** 
  249.   * @param user the user to set 
  250.   */  
  251.  public void setUser(String user) {  
  252.   this.user = user;  
  253.  }  
  254. }  
  255.   
  256. -------------------------------------------  
  257.  DBConnectionManager .java  
  258. ------------------------------------------  
  259. /** 
  260.  * 数据库连接池管理类 
  261.  */  
  262. import java.sql.Connection;  
  263. import java.util.ArrayList;  
  264. import java.util.Enumeration;  
  265. import java.util.HashMap;  
  266. import java.util.Hashtable;  
  267. import java.util.Iterator;  
  268. import java.util.Properties;  
  269. import java.util.Vector;  
  270. import com.chunkyo.db.ParseDSConfig;  
  271. import com.chunkyo.db.DSConfigBean;  
  272. import com.chunkyo.db.DBConnectionPool;  
  273. public class DBConnectionManager {  
  274.  static private DBConnectionManager instance;//唯一数据库连接池管理实例类  
  275.  static private int clients;                 //客户连接数  
  276.  private Vector drivers  = new Vector();//驱动信息  
  277.  private Hashtable pools=new Hashtable();//连接池  
  278.    
  279.  /** 
  280.   * 实例化管理类 
  281.   */  
  282.  public DBConnectionManager() {  
  283.   // TODO Auto-generated constructor stub  
  284.   this.init();  
  285.  }  
  286.  /** 
  287.   * 得到唯一实例管理类 
  288.   * @return 
  289.   */  
  290.  static synchronized public DBConnectionManager getInstance()  
  291.  {  
  292.   if(instance==null)  
  293.   {  
  294.    instance=new DBConnectionManager();  
  295.   }  
  296.   return instance;  
  297.     
  298.  }  
  299.  /** 
  300.   * 释放连接 
  301.   * @param name 
  302.   * @param con 
  303.   */  
  304.  public void freeConnection(String name, Connection con)  
  305.  {  
  306.   DBConnectionPool pool=(DBConnectionPool)pools.get(name);//根据关键名字得到连接池  
  307.   if(pool!=null)  
  308.   pool.freeConnection(con);//释放连接   
  309.  }  
  310.  /** 
  311.   * 得到一个连接根据连接池的名字name 
  312.   * @param name 
  313.   * @return 
  314.   */  
  315.  public Connection getConnection(String name)  
  316.  {  
  317.   DBConnectionPool pool=null;  
  318.   Connection con=null;  
  319.   pool=(DBConnectionPool)pools.get(name);//从名字中获取连接池  
  320.   con=pool.getConnection();//从选定的连接池中获得连接  
  321.   if(con!=null)  
  322.   System.out.println("得到连接。。。");  
  323.   return con;  
  324.  }  
  325.  /** 
  326.   * 得到一个连接,根据连接池的名字和等待时间 
  327.   * @param name 
  328.   * @param time 
  329.   * @return 
  330.   */  
  331.  public Connection getConnection(String name, long timeout)  
  332.  {  
  333.   DBConnectionPool pool=null;  
  334.   Connection con=null;  
  335.   pool=(DBConnectionPool)pools.get(name);//从名字中获取连接池  
  336.   con=pool.getConnection(timeout);//从选定的连接池中获得连接  
  337.   System.out.println("得到连接。。。");  
  338.   return con;  
  339.  }  
  340.  /** 
  341.   * 释放所有连接 
  342.   */  
  343.  public synchronized void release()  
  344.  {  
  345.   Enumeration allpools=pools.elements();  
  346.   while(allpools.hasMoreElements())  
  347.   {  
  348.    DBConnectionPool pool=(DBConnectionPool)allpools.nextElement();  
  349.    if(pool!=null)pool.release();  
  350.   }  
  351.   pools.clear();  
  352.  }  
  353.  /** 
  354.   * 创建连接池 
  355.   * @param props 
  356.   */  
  357.  private void createPools(DSConfigBean dsb)  
  358.  {  
  359.   DBConnectionPool dbpool=new DBConnectionPool();  
  360.   dbpool.setName(dsb.getName());  
  361.   dbpool.setDriver(dsb.getDriver());  
  362.   dbpool.setUrl(dsb.getUrl());  
  363.   dbpool.setUser(dsb.getUsername());  
  364.   dbpool.setPassword(dsb.getPassword());  
  365.   dbpool.setMaxConn(dsb.getMaxconn());  
  366.   System.out.println("ioio:"+dsb.getMaxconn());  
  367.   pools.put(dsb.getName(), dbpool);  
  368.  }  
  369.  /** 
  370.   * 初始化连接池的参数 
  371.   */  
  372.  private void init()  
  373.  {  
  374.   //加载驱动程序  
  375.   this.loadDrivers();  
  376.   //创建连接池  
  377.   Iterator alldriver=drivers.iterator();  
  378.   while(alldriver.hasNext())  
  379.   {  
  380.    this.createPools((DSConfigBean)alldriver.next());  
  381.    System.out.println("创建连接池。。。");  
  382.      
  383.   }  
  384.   System.out.println("创建连接池完毕。。。");  
  385.  }  
  386.  /** 
  387.   * 加载驱动程序 
  388.   * @param props 
  389.   */  
  390.  private void loadDrivers()  
  391.  {  
  392.   ParseDSConfig pd=new ParseDSConfig();  
  393.  //读取数据库配置文件  
  394.   drivers=pd.readConfigInfo("ds.config.xml");  
  395.   System.out.println("加载驱动程序。。。");  
  396.  }  
  397.  /** 
  398.   * @param args 
  399.   */  
  400.  public static void main(String[] args) {  
  401.   // TODO Auto-generated method stub  
  402.  }  
  403. }  
  404. ----------------------------------------  
  405. DSConfigBean.java  
  406. ----------------------------------------  
  407. /** 
  408.  * 配置文件Bean类 
  409.  */  
  410. public class DSConfigBean {  
  411.  private String type     =""//数据库类型  
  412.  private String name     =""//连接池名字  
  413.  private String driver   =""//数据库驱动  
  414.  private String url      =""//数据库url  
  415.  private String username =""//用户名  
  416.  private String password =""//密码  
  417.  private int maxconn  =0//最大连接数  
  418.  /** 
  419.   *  
  420.   */  
  421.  public DSConfigBean() {  
  422.   // TODO Auto-generated constructor stub  
  423.  }  
  424.  /** 
  425.   * @param args 
  426.   */  
  427.  public static void main(String[] args) {  
  428.   // TODO Auto-generated method stub  
  429.  }  
  430.  /** 
  431.   * @return the driver 
  432.   */  
  433.  public String getDriver() {  
  434.   return driver;  
  435.  }  
  436.  /** 
  437.   * @param driver the driver to set 
  438.   */  
  439.  public void setDriver(String driver) {  
  440.   this.driver = driver;  
  441.  }  
  442.  /** 
  443.   * @return the maxconn 
  444.   */  
  445.  public int getMaxconn() {  
  446.   return maxconn;  
  447.  }  
  448.  /** 
  449.   * @param maxconn the maxconn to set 
  450.   */  
  451.  public void setMaxconn(int maxconn) {  
  452.   this.maxconn = maxconn;  
  453.  }  
  454.  /** 
  455.   * @return the name 
  456.   */  
  457.  public String getName() {  
  458.   return name;  
  459.  }  
  460.  /** 
  461.   * @param name the name to set 
  462.   */  
  463.  public void setName(String name) {  
  464.   this.name = name;  
  465.  }  
  466.  /** 
  467.   * @return the password 
  468.   */  
  469.  public String getPassword() {  
  470.   return password;  
  471.  }  
  472.  /** 
  473.   * @param password the password to set 
  474.   */  
  475.  public void setPassword(String password) {  
  476.   this.password = password;  
  477.  }  
  478.  /** 
  479.   * @return the type 
  480.   */  
  481.  public String getType() {  
  482.   return type;  
  483.  }  
  484.  /** 
  485.   * @param type the type to set 
  486.   */  
  487.  public void setType(String type) {  
  488.   this.type = type;  
  489.  }  
  490.  /** 
  491.   * @return the url 
  492.   */  
  493.  public String getUrl() {  
  494.   return url;  
  495.  }  
  496.  /** 
  497.   * @param url the url to set 
  498.   */  
  499.  public void setUrl(String url) {  
  500.   this.url = url;  
  501.  }  
  502.  /** 
  503.   * @return the username 
  504.   */  
  505.  public String getUsername() {  
  506.   return username;  
  507.  }  
  508.  /** 
  509.   * @param username the username to set 
  510.   */  
  511.  public void setUsername(String username) {  
  512.   this.username = username;  
  513.  }  
  514. }  
  515. -----------------------------------------------------  
  516. ParseDSConfig.java  
  517. -----------------------------------------------------  
  518. /** 
  519.  * 操作配置文件类 读  写 修改 删除等操作  
  520.  */  
  521. import java.io.FileInputStream;  
  522. import java.io.FileNotFoundException;  
  523. import java.io.FileOutputStream;  
  524. import java.io.IOException;  
  525. import java.io.InputStream;  
  526. import java.util.List;  
  527. import java.util.Vector;  
  528. import java.util.Iterator;  
  529. import org.jdom.Document;  
  530. import org.jdom.Element;  
  531. import org.jdom.JDOMException;  
  532. import org.jdom.input.SAXBuilder;  
  533. import org.jdom.output.Format;  
  534. import org.jdom.output.XMLOutputter;  
  535. public class ParseDSConfig {  
  536.  /** 
  537.   * 构造函数 
  538.   */  
  539.  public ParseDSConfig() {  
  540.   // TODO Auto-generated constructor stub  
  541.  }  
  542.  /** 
  543.   * 读取xml配置文件 
  544.   * @param path 
  545.   * @return 
  546.   */  
  547.  public Vector readConfigInfo(String path)  
  548.  {  
  549.   String rpath=this.getClass().getResource("").getPath().substring(1)+path;  
  550.   Vector dsConfig=null;  
  551.   FileInputStream fi = null;  
  552.   try  
  553.   {  
  554.    fi=new FileInputStream(rpath);//读取路径文件  
  555.    dsConfig=new Vector();  
  556.    SAXBuilder sb=new SAXBuilder();  
  557.    Document doc=sb.build(fi);  
  558.    Element root=doc.getRootElement();  
  559.    List pools=root.getChildren();  
  560.    Element pool=null;  
  561.    Iterator allPool=pools.iterator();  
  562.    while(allPool.hasNext())  
  563.    {  
  564.     pool=(Element)allPool.next();  
  565.     DSConfigBean dscBean=new DSConfigBean();  
  566.     dscBean.setType(pool.getChild("type").getText());  
  567.     dscBean.setName(pool.getChild("name").getText());  
  568.     System.out.println(dscBean.getName());  
  569.     dscBean.setDriver(pool.getChild("driver").getText());  
  570.     dscBean.setUrl(pool.getChild("url").getText());  
  571.     dscBean.setUsername(pool.getChild("username").getText());  
  572.     dscBean.setPassword(pool.getChild("password").getText());  
  573.     dscBean.setMaxconn(Integer.parseInt(pool.getChild("maxconn").getText()));  
  574.     dsConfig.add(dscBean);  
  575.    }  
  576.      
  577.   } catch (FileNotFoundException e) {  
  578.    // TODO Auto-generated catch block  
  579.    e.printStackTrace();  
  580.   } catch (JDOMException e) {  
  581.    // TODO Auto-generated catch block  
  582.    e.printStackTrace();  
  583.   } catch (IOException e) {  
  584.    // TODO Auto-generated catch block  
  585.    e.printStackTrace();  
  586.   }  
  587.     
  588.   finally  
  589.   {  
  590.    try {  
  591.     fi.close();  
  592.    } catch (IOException e) {  
  593.     // TODO Auto-generated catch block  
  594.     e.printStackTrace();  
  595.    }  
  596.   }  
  597.     
  598.   return dsConfig;  
  599.  }  
  600.   
  601. /** 
  602.  *修改配置文件 没时间写 过段时间再贴上去 其实一样的  
  603.  */  
  604.  public void modifyConfigInfo(String path,DSConfigBean dsb) throws Exception  
  605.  {  
  606.   String rpath=this.getClass().getResource("").getPath().substring(1)+path;  
  607.   FileInputStream fi=null//读出  
  608.   FileOutputStream fo=null//写入  
  609.     
  610.  }  
  611. /** 
  612.  *增加配置文件 
  613.  * 
  614.  */  
  615.  public void addConfigInfo(String path,DSConfigBean dsb)   
  616.  {  
  617.   String rpath=this.getClass().getResource("").getPath().substring(1)+path;  
  618.   FileInputStream fi=null;  
  619.   FileOutputStream fo=null;  
  620.   try  
  621.   {  
  622.    fi=new FileInputStream(rpath);//读取xml流  
  623.      
  624.    SAXBuilder sb=new SAXBuilder();  
  625.      
  626.    Document doc=sb.build(fi); //得到xml  
  627.    Element root=doc.getRootElement();  
  628.    List pools=root.getChildren();//得到xml子树  
  629.      
  630.    Element newpool=new Element("pool"); //创建新连接池  
  631.      
  632.    Element pooltype=new Element("type"); //设置连接池类型  
  633.    pooltype.setText(dsb.getType());  
  634.    newpool.addContent(pooltype);  
  635.      
  636.    Element poolname=new Element("name");//设置连接池名字  
  637.    poolname.setText(dsb.getName());  
  638.    newpool.addContent(poolname);  
  639.      
  640.    Element pooldriver=new Element("driver"); //设置连接池驱动  
  641.    pooldriver.addContent(dsb.getDriver());  
  642.    newpool.addContent(pooldriver);  
  643.      
  644.    Element poolurl=new Element("url");//设置连接池url  
  645.    poolurl.setText(dsb.getUrl());  
  646.    newpool.addContent(poolurl);  
  647.      
  648.    Element poolusername=new Element("username");//设置连接池用户名  
  649.    poolusername.setText(dsb.getUsername());  
  650.    newpool.addContent(poolusername);  
  651.      
  652.    Element poolpassword=new Element("password");//设置连接池密码  
  653.    poolpassword.setText(dsb.getPassword());  
  654.    newpool.addContent(poolpassword);  
  655.      
  656.    Element poolmaxconn=new Element("maxconn");//设置连接池最大连接  
  657.    poolmaxconn.setText(String.valueOf(dsb.getMaxconn()));  
  658.    newpool.addContent(poolmaxconn);  
  659.    pools.add(newpool);//将child添加到root  
  660.    Format format = Format.getPrettyFormat();  
  661.       format.setIndent("");  
  662.       format.setEncoding("utf-8");  
  663.       XMLOutputter outp = new XMLOutputter(format);  
  664.       fo = new FileOutputStream(rpath);  
  665.       outp.output(doc, fo);  
  666.   } catch (FileNotFoundException e) {  
  667.    // TODO Auto-generated catch block  
  668.    e.printStackTrace();  
  669.   } catch (JDOMException e) {  
  670.    // TODO Auto-generated catch block  
  671.    e.printStackTrace();  
  672.   } catch (IOException e) {  
  673.    // TODO Auto-generated catch block  
  674.    e.printStackTrace();  
  675.   }  
  676.   finally  
  677.   {  
  678.      
  679.   }  
  680.  }  
  681.  /** 
  682.   *删除配置文件 
  683.   */  
  684.  public void delConfigInfo(String path,String name)  
  685.  {  
  686.   String rpath=this.getClass().getResource("").getPath().substring(1)+path;  
  687.   FileInputStream fi = null;  
  688.   FileOutputStream fo=null;  
  689.   try  
  690.   {  
  691.    fi=new FileInputStream(rpath);//读取路径文件  
  692.    SAXBuilder sb=new SAXBuilder();  
  693.    Document doc=sb.build(fi);  
  694.    Element root=doc.getRootElement();  
  695.    List pools=root.getChildren();  
  696.    Element pool=null;  
  697.    Iterator allPool=pools.iterator();  
  698.    while(allPool.hasNext())  
  699.    {  
  700.     pool=(Element)allPool.next();  
  701.     if(pool.getChild("name").getText().equals(name))  
  702.     {  
  703.      pools.remove(pool);  
  704.      break;  
  705.     }  
  706.    }  
  707.    Format format = Format.getPrettyFormat();  
  708.       format.setIndent("");  
  709.       format.setEncoding("utf-8");  
  710.       XMLOutputter outp = new XMLOutputter(format);  
  711.       fo = new FileOutputStream(rpath);  
  712.       outp.output(doc, fo);  
  713.      
  714.   } catch (FileNotFoundException e) {  
  715.    // TODO Auto-generated catch block  
  716.    e.printStackTrace();  
  717.   } catch (JDOMException e) {  
  718.    // TODO Auto-generated catch block  
  719.    e.printStackTrace();  
  720.   } catch (IOException e) {  
  721.    // TODO Auto-generated catch block  
  722.    e.printStackTrace();  
  723.   }  
  724.     
  725.   finally  
  726.   {  
  727.    try {  
  728.     fi.close();  
  729.    } catch (IOException e) {  
  730.     // TODO Auto-generated catch block  
  731.     e.printStackTrace();  
  732.    }  
  733.   }  
  734.  }  
  735.  /** 
  736.   * @param args 
  737.   * @throws Exception  
  738.   */  
  739.  public static void main(String[] args) throws Exception {  
  740.   // TODO Auto-generated method stub  
  741.   ParseDSConfig pd=new ParseDSConfig();  
  742.   String path="ds.config.xml";  
  743.   pd.readConfigInfo(path);  
  744.   //pd.delConfigInfo(path, "tj012006");  
  745.   DSConfigBean dsb=new DSConfigBean();  
  746.   dsb.setType("oracle");  
  747.   dsb.setName("yyy004");  
  748.   dsb.setDriver("org.oracle.jdbc");  
  749.   dsb.setUrl("jdbc:oracle://localhost");  
  750.   dsb.setUsername("sa");  
  751.   dsb.setPassword("");  
  752.   dsb.setMaxconn(1000);  
  753.   pd.addConfigInfo(path, dsb);  
  754.   pd.delConfigInfo(path, "yyy001");  
  755.  }  
  756. }  
  757.   
  758. --------------------------------------  
  759. ds.config.xml   配置文件  
  760. --------------------------------------  
  761.   
  762.   
  763. <ds-config>  
  764. <pool>  
  765. <type>mysql</type>  
  766. <name>user</name>  
  767. <driver>com.mysql.jdbc.driver</driver>  
  768. <url>jdbc:mysql://localhost:3306/user</url>  
  769. <username>sa</username>  
  770. <password>123456</password>  
  771. <maxconn>100</maxconn>  
  772. </pool>  
  773. <pool>  
  774. <type>mysql</type>  
  775. <name>user2</name>  
  776. <driver>com.mysql.jdbc.driver</driver>  
  777. <url>jdbc:mysql://localhost:3306/user2</url>  
  778. <username>sa</username>  
  779. <password>1234</password>  
  780. <maxconn>10</maxconn>  
  781. </pool>  
  782. <pool>  
  783. <type>sql2000</type>  
  784. <name>books</name>  
  785. <driver>com.microsoft.sqlserver.driver</driver>  
  786. <url>jdbc:sqlserver://localhost:1433/books:databasename=books</url>  
  787. <username>sa</username>  
  788. <password></password>  
  789. <maxconn>100</maxconn>  
  790. </pool>  
  791. </ds-config>  

3. 连接池的使用
  1).Connection的获得和释放
  DBConnectionManager   connectionMan=DBConnectionManager .getInstance();//得到唯一实例
   //得到连接
   String name="mysql";//从上下文得到你要访问的数据库的名字
   Connection  con=connectionMan.getConnection(name);
  //使用
  。。。。。。。
  // 使用完毕
 connectionMan.freeConnection(name,con);//释放,但并未断开连接
 2).数据库连接的动态增加和连接池的动态增加
      1.调用xml操作增加类

      2.重新实例华连接池管理池类
0 0
原创粉丝点击