首页 > 技术文章 > java数据库连接池

wuhailong 2016-01-21 09:32 原文

基础内容引用自 http://blog.sina.com.cn/s/blog_55d57a460100iq71.html

人做了一些修改,并封装了jdbc,不足之处请指正。

改造的原因是这样的,由于项目需求发现此数据库连接池样例只能配置一个数据库的连接,对需连多个数据库此连接池就不好用了,所以稍加改造;不多说见代码;

首先封装的jdbc

  1 package com.goodwillcis.common;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.io.UnsupportedEncodingException;
  6 import java.sql.Connection;
  7 import java.sql.DriverManager;
  8 import java.sql.ResultSet;
  9 import java.sql.ResultSetMetaData;
 10 import java.sql.SQLException;
 11 import java.sql.Statement;
 12 import java.util.HashMap;
 13 import java.util.Map;
 14 import java.util.Properties;
 15 
 16 public class CommonFunction {
 17     
 18     public CommonFunction(){
 19     } 
 20     
 21     /**
 22      * 获取config.properties配置文件中配置项�?
 23      * 2015-12-28
 24      * 吴海�?
 25      */
 26     public String GetPropertie(String p_strProName) {
 27         Properties prop = new Properties();
 28         InputStream is = this.getClass().getResourceAsStream(
 29                 "/config.properties");
 30         try {
 31             prop.load(is);
 32             String _strResult = prop.getProperty(p_strProName).trim();
 33             return _strResult;
 34         } catch (Exception e) {
 35             e.printStackTrace();
 36         }
 37         return "";
 38     }
 39     
 40     
 41     
 42     
 43     /**
 44      * 执行查询语句,参数1 sql语句 参数2 数据库连接串名称具体写法采用约定大于配置规则 
 45      * wuhailong
 46      * 2016-01-20
 47      */
 48     public static HashMap<String, HashMap<String, Object>> ExecuteQuery(String p_strSQL,String p_strDBName) {
 49         Statement stmt = null;
 50         try {
 51             String sql = p_strSQL;
 52             ConnectionPool connpool = ConnectionPool.getInstance(p_strDBName);
 53             Connection conn = connpool.getConnection(p_strDBName);;
 54             //System.out.println(sql);
 55             stmt = conn.createStatement();
 56             ResultSet rs = stmt.executeQuery(sql);
 57             HashMap<String, HashMap<String, Object>> table =FixData(rs);
 58             connpool.returnConnection(conn,p_strDBName);
 59             return table;
 60         } catch (Exception e) {
 61             e.printStackTrace();
 62             return null;
 63         }finally{
 64             if(stmt!=null){
 65                 try {
 66                     stmt.close();
 67                 } catch (SQLException e) {
 68                     // TODO Auto-generated catch block
 69                     e.printStackTrace();
 70                 }
 71             }
 72         }
 73     }
 74     
     //将resultset 转化为 一个hashmap 75 public static HashMap<String, HashMap<String, Object>> FixData(ResultSet p_rsData) throws SQLException, UnsupportedEncodingException{ 76 HashMap<String, HashMap<String, Object>> table = new HashMap<String,HashMap<String,Object>>(); 77 ResultSetMetaData rsmd; 78 rsmd = p_rsData.getMetaData(); 79 int numCols = rsmd.getColumnCount(); 80 int rownum = 0; 81 while (p_rsData.next()) { 82 HashMap<String, Object> row = new HashMap<String, Object>(); 83 for(int columnindex = 1;columnindex<=numCols;columnindex++){ 84 String _strComunName =rsmd.getColumnName(columnindex); 85 Object _objValue = p_rsData.getObject(_strComunName)==null?"":p_rsData.getObject(_strComunName); 86 //String _strValue = new String(_objValue.toString().getBytes("iso-8859-1"), "GBK"); 87 row.put(_strComunName.toUpperCase(), _objValue); 88 } 89 table.put(rownum+"", row); 90 rownum++; 91 //System.out.println(rownum); 92 } 93 return table; 94 } 95 96 /** 97 * 执行增删改操作 参数1 sql语句 参数2 数据库名 98 * wuhailong 99 * 2016-01-20 100 * @throws SQLException 101 */ 102 public static int ExecuteNonQuery(String p_strSQL,String p_strDBName) { 103 Statement stmt= null; 104 try { 105 String sql = p_strSQL; 106 //System.out.println(sql); 107 ConnectionPool connpool = ConnectionPool.getInstance(p_strDBName); 108 Connection conn = connpool.getConnection(p_strDBName); 109 stmt = conn.createStatement(); 110 int _n = stmt.executeUpdate(sql); 111 connpool.returnConnection(conn,p_strDBName); 112 return _n; 113 } catch (Exception e) { 114 e.printStackTrace(); 115 return -1; 116 }finally{ 117 if(stmt!=null){ 118 try { 119 stmt.close(); 120 } catch (SQLException e) { 121 // TODO Auto-generated catch block 122 e.printStackTrace(); 123 } 124 } 125 } 126 } 127 128

 

数据库连接池代码

  1 package com.goodwillcis.common;
  2 
  3 import java.sql.Connection;
  4 import java.sql.DatabaseMetaData;
  5 import java.sql.Driver;
  6 import java.sql.DriverManager;
  7 import java.sql.ResultSet;
  8 import java.sql.SQLException;
  9 import java.sql.Statement;
 10 import java.util.Enumeration;
 11 import java.util.HashMap;
 12 import java.util.Map;
 13 import java.util.Vector;
 14 
 15 public class ConnectionPool {
 16 
 17     private String jdbcDriver = ""; // 数据库驱�?
 18     private String dbUrl = ""; // 数据 URL
 19     private String dbUsername = ""; // 数据库用户名
 20     private String dbPassword = ""; // 数据库用户密�?
 21     private String testTable = ""; // 测试连接是否可用的测试表名,默认没有测试�?
 22     private int initialConnections = 20; // 连接池的初始大小
 23     private int incrementalConnections = 5;// 连接池自动增加的大小
 24     private int maxConnections = 50; // 连接池最大的大小
 25     private Vector connections = null; // 存放连接池中数据库连接的向量 , 初始时为 null
 26     private Map<String,Vector>  connectionsmap =null; // 存放连接池中数据库连接的向量 , 初始时为 null
 27     // 它中存放的对象为 PooledConnection �?
 28     private static ConnectionPool instance = null;
 29     private static Map<String,ConnectionPool> instances = new HashMap<String,ConnectionPool>();
 30     
 31     public static ConnectionPool getInstance() {
 32         if (instance == null) {
 33             synchronized (ConnectionPool.class) {
 34                 if (instance == null) {
 35                     instance = new ConnectionPool();
 36                 }
 37             }
 38         }
 39         try {
 40             instance.createPool();
 41         } catch (Exception e) {
 42             e.printStackTrace();
 43         }
 44         return instance;
 45     }
 46     
 47     /**
 48      * create a hashmap connectionpool the key is dbname value is connectionpool
 49      * you can get the connectionpool with dbname
 50      * 2016-01-20 
 51      * wuhailong
 52      * @param p_strDBName
 53      * @return
 54      * @throws Exception 
 55      */
 56     public static ConnectionPool getInstance(String p_strDBName) throws Exception {
 57         ConnectionPool cp = null;
 58         if (instances == null) {
 59             instances = new HashMap<String, ConnectionPool>();
 60         } else {
 61             if (instances.get(p_strDBName) == null) {
 62                 cp= new ConnectionPool(p_strDBName);
 63                 instances.put(p_strDBName, cp);
 64                 cp.createPool(p_strDBName);
 65             }
 66         }
 67         return instances.get(p_strDBName);
 68     }
 69 
 70     
 71     /**
 72      * Ĭ��Db_ConnString��Db_User��Db_Password��Db_Driver
 73      */
 74     private ConnectionPool() {
 75         CommonFunction c = new CommonFunction();
 76         String Db_ConnString =c.GetPropertie("Db_ConnString");
 77         String Db_User =c.GetPropertie("Db_User");
 78         String Db_Password =c.GetPropertie("Db_Password");
 79         String Db_Driver =c.GetPropertie("Db_Driver");
 80         this.jdbcDriver = Db_Driver;//"oracle.jdbc.driver.OracleDriver";
 81         this.dbUrl = Db_ConnString;
 82         this.dbUsername = Db_User;
 83         this.dbPassword = Db_Password;
 84     }
 85     
 86     
 87     /**
 88      * ָ������
 89      * @param p_strDiver
 90      * @param p_strConnectionString
 91      * @param p_strUser
 92      * @param p_strPsw
 93      */
 94     private ConnectionPool(String p_strDBName) {
 95         CommonFunction c = new CommonFunction();
 96         String Db_ConnString =c.GetPropertie(p_strDBName+"_Db_ConnString");
 97         String Db_User =c.GetPropertie(p_strDBName+"_Db_User");
 98         String Db_Password =c.GetPropertie(p_strDBName+"_Db_Password");
 99         String Db_Driver =c.GetPropertie(p_strDBName+"_Db_Driver");
100         this.jdbcDriver = Db_Driver;
101         this.dbUrl = Db_ConnString;
102         this.dbUsername = Db_User;
103         this.dbPassword = Db_Password;
104     }
105 
106     /**
107      * 创建�?��数据库连接池,连接池中的可用连接的数量采用类成员 initialConnections 中设置的�?
108      */
109 
110     public synchronized void createPool() throws Exception {
111         // 确保连接池没有创�?
112         // 如果连接池己经创建了,保存连接的向量 connections 不会为空
113         if (connections != null) {
114             return; // 如果己经创建,则返回
115         }
116         // 实例�?JDBC Driver 中指定的驱动类实�?
117         Driver driver = (Driver) (Class.forName(this.jdbcDriver).newInstance());
118         DriverManager.registerDriver(driver); // 注册 JDBC 驱动程序
119         // 创建保存连接的向�?, 初始时有 0 个元�?
120         connections = new Vector();
121         // 根据 initialConnections 中设置的值,创建连接�?
122         createConnections(this.initialConnections);
123         System.out.println(" 数据库连接池创建成功�?");
124     }
125 
126     public synchronized void createPool(String p_strDBName) throws Exception {
127         if (connectionsmap != null) {
128             return; // 如果己经创建,则返回
129         }
130         CommonFunction cf = new CommonFunction();
131         String _strDriver = cf.GetPropertie(p_strDBName+"_Db_Driver");
132         Driver driver = (Driver) (Class.forName(_strDriver).newInstance());
133         DriverManager.registerDriver(driver);
134         Vector conns = new Vector();
135         connectionsmap = new HashMap<String,Vector>();
136         connectionsmap.put(p_strDBName, conns);
137         createConnections(this.initialConnections,p_strDBName);
138         
139         System.out.println(" connectionpool created");
140     }
141 
142     
143     /**
144      * 
145      * 创建�?numConnections 指定数目的数据库连接 , 并把这些连接
146      * 
147      * 放入 connections 向量�?
148      * 
149      * 
150      * 
151      * @param numConnections
152      *            要创建的数据库连接的数目
153      * 
154      */
155 
156     @SuppressWarnings("unchecked")
157     private void createConnections(int numConnections) throws SQLException {
158         // 循环创建指定数目的数据库连接
159         for (int x = 0; x < numConnections; x++) {
160 
161             // 是否连接池中的数据库连接的数量己经达到最大?�?��值由类成�?maxConnections
162             // 指出,如�?maxConnections �?0 或负数,表示连接数量没有限制�?
163             // 如果连接数己经达到最大,即�?出�?
164             
165             if (this.maxConnections > 0
166                     && this.connections.size() >= this.maxConnections) {
167                 break;
168             }
169             // add a new PooledConnection object to connections vector
170             // 增加�?��连接到连接池中(向量 connections 中)
171             try {
172                 connections.addElement(new PooledConnection(newConnection()));
173             } catch (SQLException e) {
174                 System.out.println(" 创建数据库连接失败! " + e.getMessage());
175                 throw new SQLException();
176             }
177             System.out.println(" created connection "+x);
178         }
179     }
180     
181     @SuppressWarnings("unchecked")
182     private void createConnections(int numConnections,String p_strDBName) throws SQLException {
183         // 循环创建指定数目的数据库连接
184         for (int x = 0; x < numConnections; x++) {
185 
186             // 是否连接池中的数据库连接的数量己经达到最大?�?��值由类成�?maxConnections
187             // 指出,如�?maxConnections �?0 或负数,表示连接数量没有限制�?
188             // 如果连接数己经达到最大,即�?出�?
189             Vector connections =connectionsmap.get(p_strDBName);
190             if (this.maxConnections > 0
191                     && connections.size() >= this.maxConnections) {
192                 break;
193             }
194             // add a new PooledConnection object to connections vector
195             // 增加�?��连接到连接池中(向量 connections 中)
196             try {
197                 connections.addElement(new PooledConnection(newConnection(p_strDBName)));
198             } catch (SQLException e) {
199                 System.out.println(" connection false... " + e.getMessage());
200                 throw new SQLException();
201             }
202             System.out.println(" connection created..."+x);
203         }
204     }
205     
206     private void createConnections(String p_strDBName,int numConnections) throws SQLException {
207         // 循环创建指定数目的数据库连接
208         for (int x = 0; x < numConnections; x++) {
209 
210             // 是否连接池中的数据库连接的数量己经达到最大?�?��值由类成�?maxConnections
211             // 指出,如�?maxConnections �?0 或负数,表示连接数量没有限制�?
212             // 如果连接数己经达到最大,即�?出�?
213             Vector   _vConn = connectionsmap.get(p_strDBName);
214             if (this.maxConnections > 0
215                     && _vConn.size() >= this.maxConnections) {
216                 break;
217             }
218             // add a new PooledConnection object to connections vector
219             // 增加�?��连接到连接池中(向量 connections 中)
220             try {
221                 _vConn.addElement(new PooledConnection(newConnection(p_strDBName)));
222             } catch (SQLException e) {
223                 System.out.println(" 创建数据库连接失败! " + e.getMessage());
224                 throw new SQLException();
225             }
226             System.out.println(" 数据库连接己创建 ......");
227         }
228     }
229 
230     /**
231      * 
232      * 创建�?��新的数据库连接并返回�?
233      * 
234      * 
235      * 
236      * @return 返回�?��新创建的数据库连�?
237      * 
238      */
239 
240     private Connection newConnection() throws SQLException {
241 
242         // 创建�?��数据库连�?
243 
244         Connection conn = DriverManager.getConnection(dbUrl, dbUsername,
245                 dbPassword);
246         // 如果这是第一次创建数据库连接,即�?��数据库,获得此数据库允许支持�?
247         // �?��客户连接数目
248         // connections.size()==0 表示目前没有连接己被创建
249         if (connections.size() == 0) {
250             DatabaseMetaData metaData = conn.getMetaData();
251             int driverMaxConnections = metaData.getMaxConnections();
252             // 数据库返回的 driverMaxConnections 若为 0 ,表示此数据库没有最�?
253             // 连接限制,或数据库的�?��连接限制不知�?
254             // driverMaxConnections 为返回的�?��整数,表示此数据库允许客户连接的数目
255             // 如果连接池中设置的最大连接数量大于数据库允许的连接数�?, 则置连接池的�?��
256             // 连接数目为数据库允许的最大数�?
257             if (driverMaxConnections > 0
258                     && this.maxConnections > driverMaxConnections) {
259                 this.maxConnections = driverMaxConnections;
260             }
261         }
262         return conn; // 返回创建的新的数据库连接
263     }
264     
265     private Connection newConnection(String p_strDBName) throws SQLException {
266 
267         // 创建�?��数据库连�?
268 
269         CommonFunction cf = new CommonFunction();
270         String _strUrl = cf.GetPropertie(p_strDBName+"_Db_ConnString");
271         String _strUser = cf.GetPropertie(p_strDBName+"_Db_User");
272         String _strPsw = cf.GetPropertie(p_strDBName+"_Db_Password");
273         Connection conn = DriverManager.getConnection(_strUrl, _strUser,
274                 _strPsw);
275         Vector connections= connectionsmap.get(p_strDBName);
276         if (connections.size() == 0) {
277             DatabaseMetaData metaData = conn.getMetaData();
278             int driverMaxConnections = metaData.getMaxConnections();
279             if (driverMaxConnections > 0
280                     && this.maxConnections > driverMaxConnections) {
281                 this.maxConnections = driverMaxConnections;
282             }
283         }
284         return conn; // 返回创建的新的数据库连接
285     }
286 
287     /**
288      * 
289      * 通过调用 getFreeConnection() 函数返回�?��可用的数据库连接 ,
290      * 
291      * 如果当前没有可用的数据库连接,并且更多的数据库连接不能创建(如连接池大小的限制),此函数等待�?��再尝试获取�?
292      * 
293      * @return 返回�?��可用的数据库连接对象
294      * 
295      */
296 
297     public synchronized Connection getConnection() throws SQLException {
298         // 确保连接池己被创�?
299         if (connections == null) {
300             return null; // 连接池还没创建,则返�?null
301         }
302         Connection conn = getFreeConnection(); // 获得�?��可用的数据库连接
303         // 如果目前没有可以使用的连接,即所有的连接都在使用�?
304         while (conn == null) {
305             // 等一会再�?
306             wait(250);
307             System.out.println("连接为空正在等待创建");
308             conn = getFreeConnection(); // 重新再试,直到获得可用的连接,如�?
309             // getFreeConnection() 返回的为 null
310             // 则表明创建一批连接后也不可获得可用连�?
311         }
312         return conn;// 返回获得的可用的连接
313     }
314 
315     
316     public synchronized Connection getConnection(String p_strDBName) throws SQLException {
317         // 确保连接池己被创�?
318         Vector connections=connectionsmap.get(p_strDBName);
319         if (connections == null) {
320             return null; // 连接池还没创建,则返�?null
321         }
322         Connection conn = getFreeConnection(p_strDBName); // 获得�?��可用的数据库连接
323         // 如果目前没有可以使用的连接,即所有的连接都在使用�?
324         while (conn == null) {
325             // 等一会再�?
326             wait(250);
327             System.out.println("连接为空正在等待创建");
328             conn = getFreeConnection(p_strDBName); // 重新再试,直到获得可用的连接,如�?
329             // getFreeConnection() 返回的为 null
330             // 则表明创建一批连接后也不可获得可用连�?
331         }
332         return conn;// 返回获得的可用的连接
333     }
334 
335     
336     /**
337      * 
338      * 本函数从连接池向�?connections 中返回一个可用的的数据库连接,如�?
339      * 
340      * 当前没有可用的数据库连接,本函数则根�?incrementalConnections 设置
341      * 
342      * 的�?创建几个数据库连接,并放入连接池中�?
343      * 
344      * 如果创建后,�?��的连接仍都在使用中,则返�?null
345      * 
346      * @return 返回�?��可用的数据库连接
347      * 
348      */
349 
350     private Connection getFreeConnection() throws SQLException {
351 
352         // 从连接池中获得一个可用的数据库连�?
353         Connection conn = findFreeConnection();
354         if (conn == null) {
355             // 如果目前连接池中没有可用的连�?
356             // 创建�?��连接
357             createConnections(incrementalConnections);
358             // 重新从池中查找是否有可用连接
359             conn = findFreeConnection();
360             if (conn == null) {
361                 // 如果创建连接后仍获得不到可用的连接,则返�?null
362             }
363 
364         }
365         return conn;
366     }
367     
368     private Connection getFreeConnection(String p_strDBName) throws SQLException {
369 
370         // 从连接池中获得一个可用的数据库连�?
371         Connection conn = findFreeConnection(p_strDBName);
372         if (conn == null) {
373             // 如果目前连接池中没有可用的连�?
374             // 创建�?��连接
375             createConnections(incrementalConnections,p_strDBName);
376             // 重新从池中查找是否有可用连接
377             conn = findFreeConnection(p_strDBName);
378             if (conn == null) {
379                 // 如果创建连接后仍获得不到可用的连接,则返�?null
380             }
381 
382         }
383         return conn;
384     }
385 
386     /**
387      * 
388      * 查找连接池中�?��的连接,查找�?��可用的数据库连接�?
389      * 
390      * 如果没有可用的连接,返回 null
391      * 
392      * 
393      * 
394      * @return 返回�?��可用的数据库连接
395      * 
396      */
397 
398     private Connection findFreeConnection() throws SQLException {
399         Connection conn = null;
400         PooledConnection pConn = null;
401         // 获得连接池向量中�?��的对�?
402         Enumeration enumerate = connections.elements();
403         // 遍历�?��的对象,看是否有可用的连�?
404         while (enumerate.hasMoreElements()) {
405             pConn = (PooledConnection) enumerate.nextElement();
406             if (!pConn.isBusy()) {
407                 // 如果此对象不忙,则获得它的数据库连接并把它设为忙
408                 conn = pConn.getConnection();
409                 pConn.setBusy(true);
410                 // 测试此连接是否可�?
411                 if (!testConnection(conn)) {
412                     // 如果此连接不可再用了,则创建�?��新的连接�?
413                     // 并替换此不可用的连接对象,如果创建失败,返回 null
414                     try {
415                         conn = newConnection();
416                     } catch (SQLException e) {
417 
418                         System.out.println(" 创建数据库连接失败! " + e.getMessage());
419 
420                         return null;
421                     }
422                     pConn.setConnection(conn);
423                 }
424                 break; // 己经找到�?��可用的连接,�?��
425             }
426         }
427         return conn;// 返回找到到的可用连接
428     }
429     
430     
431     private Connection findFreeConnection(String p_strDBName){
432         Connection conn = null;
433         PooledConnection pConn = null;
434         Vector connections =connectionsmap.get(p_strDBName);
435         Enumeration enumerate = connections.elements();
436         while (enumerate.hasMoreElements()) {
437             pConn = (PooledConnection) enumerate.nextElement();
438             if (!pConn.isBusy()) {
439                 conn = pConn.getConnection();
440                 pConn.setBusy(true);
441                 if (!testConnection(conn)) {
442                     try {
443                         conn = newConnection();
444                     } catch (SQLException e) {
445                         System.out.println(" 创建数据库连接失败! " + e.getMessage());
446                         return null;
447                     }
448                     pConn.setConnection(conn);
449                 }
450                 break; 
451             }
452         }
453         return conn;
454     }
455 
456     /**
457      * 测试�?��连接是否可用,如果不可用,关掉它并返�?false 否则可用返回 true
458      * 
459      * @param conn
460      *            �?��测试的数据库连接
461      * @return 返回 true 表示此连接可用, false 表示不可�?
462      */
463 
464     private boolean testConnection(Connection conn) {
465         try {
466             // 判断测试表是否存�?
467             if (testTable.equals("")) {
468                 // 如果测试表为空,试着使用此连接的 setAutoCommit() 方法
469                 // 来判断连接否可用(此方法只在部分数据库可用,如果不可�?,
470                 // 抛出异常)�?注意:使用测试表的方法更可靠
471                 conn.setAutoCommit(true);
472             } else {// 有测试表的时候使用测试表测试
473                 // check if this connection is valid
474                 Statement stmt = conn.createStatement();
475                 ResultSet rs = stmt.executeQuery("select count(*) from "
476                         + testTable);
477                 rs.next();
478                 System.out.println(testTable + ":表的记录数为:" + rs.getInt(1));
479             }
480         } catch (SQLException e) {
481             // 上面抛出异常,此连接己不可用,关闭它,并返回 false;
482             e.printStackTrace();
483             closeConnection(conn);
484             return false;
485         }
486         // 连接可用,返�?true
487         return true;
488     }
489 
490     /**
491      * 此函数返回一个数据库连接到连接池中,并把此连接置为空闲�?
492      * 
493      * �?��使用连接池获得的数据库连接均应在不使用此连接时返回它�?
494      * 
495      * @param �?��回到连接池中的连接对�?
496      */
497 
498     public void returnConnection(Connection conn) {
499 
500         // 确保连接池存在,如果连接没有创建(不存在),直接返回
501         if (connections == null) {
502             System.out.println(" 连接池不存在,无法返回此连接到连接池�?!");
503             return;
504         }
505         PooledConnection pConn = null;
506         Enumeration enumerate = connections.elements();
507         // 遍历连接池中的所有连接,找到这个要返回的连接对象
508         while (enumerate.hasMoreElements()) {
509             pConn = (PooledConnection) enumerate.nextElement();
510             // 先找到连接池中的要返回的连接对象
511             if (conn == pConn.getConnection()) {
512                 // 找到�?, 设置此连接为空闲状�?
513                 pConn.setBusy(false);
514                 break;
515             }
516         }
517     }
518     
519     public void returnConnection(Connection conn,String p_strDBName) {
520         // 确保连接池存在,如果连接没有创建(不存在),直接返回
521         Vector connections = connectionsmap.get(p_strDBName);
522         if (connections == null) {
523             System.out.println(" 连接池不存在,无法返回此连接到连接池�?!");
524             return;
525         }
526         PooledConnection pConn = null;
527         Enumeration enumerate = connections.elements();
528         // 遍历连接池中的所有连接,找到这个要返回的连接对象
529         while (enumerate.hasMoreElements()) {
530             pConn = (PooledConnection) enumerate.nextElement();
531             // 先找到连接池中的要返回的连接对象
532             if (conn == pConn.getConnection()) {
533                 // 找到�?, 设置此连接为空闲状�?
534                 pConn.setBusy(false);
535                 break;
536             }
537         }
538     }
539 
540     /**
541      * 刷新连接池中�?��的连接对�?
542      */
543     public synchronized void refreshConnections() throws SQLException {
544         // 确保连接池己创新存在
545         if (connections == null) {
546             System.out.println(" 连接池不存在,无法刷�?!");
547             return;
548         }
549         PooledConnection pConn = null;
550         Enumeration enumerate = connections.elements();
551         while (enumerate.hasMoreElements()) {
552             // 获得�?��连接对象
553             pConn = (PooledConnection) enumerate.nextElement();
554             // 如果对象忙则�?5 �?,5 秒后直接刷新
555             if (pConn.isBusy()) {
556                 wait(5000); // �?5 �?
557             }
558             // 关闭此连接,用一个新的连接代替它�?
559             closeConnection(pConn.getConnection());
560             pConn.setConnection(newConnection());
561             pConn.setBusy(false);
562         }
563     }
564 
565     /**
566      * 关闭连接池中�?��的连接,并清空连接池�?
567      */
568     public synchronized void closeConnectionPool() throws SQLException {
569         // 确保连接池存在,如果不存在,返回
570         if (connections == null) {
571             System.out.println(" 连接池不存在,无法关�?!");
572             return;
573         }
574         PooledConnection pConn = null;
575         Enumeration enumerate = connections.elements();
576         while (enumerate.hasMoreElements()) {
577             pConn = (PooledConnection) enumerate.nextElement();
578             // 如果忙,�?5 �?
579             if (pConn.isBusy()) {
580                 wait(5000); // �?5 �?
581             }
582 
583             // 5 秒后直接关闭�?
584             closeConnection(pConn.getConnection());
585             // 从连接池向量中删除它
586             connections.removeElement(pConn);
587         }
588 
589         // 置连接池为空
590         connections = null;
591     }
592 
593     /**
594      * 关闭�?��数据库连�?
595      * 
596      * @param �?��关闭的数据库连接
597      */
598 
599     private void closeConnection(Connection conn) {
600         try {
601             conn.close();
602         } catch (SQLException e) {
603             System.out.println(" 关闭数据库连接出错: " + e.getMessage());
604         }
605 
606     }
607 
608     /**
609      * 使程序等待给定的毫秒�?
610      * 
611      * @param 给定的毫秒数
612      */
613 
614     private void wait(int mSeconds) {
615         try {
616             Thread.sleep(mSeconds);
617         } catch (InterruptedException e) {
618         }
619 
620     }
621 
622     /**
623      * 返回连接池的初始大小
624      * 
625      * @return 初始连接池中可获得的连接数量
626      */
627 
628     public int getInitialConnections() {
629         return this.initialConnections;
630     }
631 
632     /**
633      * 设置连接池的初始大小
634      * 
635      * @param 用于设置初始连接池中连接的数�?
636      */
637 
638     public void setInitialConnections(int initialConnections) {
639         this.initialConnections = initialConnections;
640     }
641 
642     /**
643      * 返回连接池自动增加的大小 �?
644      * 
645      * @return 连接池自动增加的大小
646      */
647 
648     public int getIncrementalConnections() {
649         return this.incrementalConnections;
650     }
651 
652     /**
653      * 设置连接池自动增加的大小
654      * 
655      * @param 连接池自动增加的大小
656      */
657 
658     public void setIncrementalConnections(int incrementalConnections) {
659         this.incrementalConnections = incrementalConnections;
660     }
661 
662     /**
663      * 返回连接池中�?��的可用连接数�?
664      * 
665      * @return 连接池中�?��的可用连接数�?
666      */
667 
668     public int getMaxConnections() {
669         return this.maxConnections;
670     }
671 
672     /**
673      * 设置连接池中�?��可用的连接数�?
674      * 
675      * @param 设置连接池中�?��可用的连接数量�?
676      */
677 
678     public void setMaxConnections(int maxConnections) {
679         this.maxConnections = maxConnections;
680     }
681 
682     /**
683      * 获取测试数据库表的名�?
684      * 
685      * @return 测试数据库表的名�?
686      */
687 
688     public String getTestTable() {
689         return this.testTable;
690     }
691 
692     /**
693      * 设置测试表的名字
694      * 
695      * @param testTable
696      *            String 测试表的名字
697      */
698 
699     public void setTestTable(String testTable) {
700         this.testTable = testTable;
701     }
702 
703     /**
704      * 内部使用的用于保存连接池中连接对象的�?
705      * 
706      * 此类中有两个成员,一个是数据库的连接,另�?��是指示此连接是否
707      * 
708      * 正在使用的标志�?
709      */
710 
711     class PooledConnection {
712         Connection connection = null;// 数据库连�?
713         boolean busy = false; // 此连接是否正在使用的标志,默认没有正在使�?
714         // 构�?函数,根据一�?Connection 构告�?�� PooledConnection 对象
715         public PooledConnection(Connection connection) {
716             this.connection = connection;
717         }
718 
719         // 返回此对象中的连�?
720         public Connection getConnection() {
721             return connection;
722         }
723 
724         // 设置此对象的,连�?
725 
726         public void setConnection(Connection connection) {
727             this.connection = connection;
728         }
729 
730         // 获得对象连接是否�?
731 
732         public boolean isBusy() {
733             return busy;
734         }
735 
736         // 设置对象的连接正在忙
737 
738         public void setBusy(boolean busy) {
739             this.busy = busy;
740         }
741 
742     }
743 
744 }

 

配置文件代码

 

 1 Db_Type=ORACLE
 2 
 3 #临床路径数据库连接串
 4 Cp_Db_ConnString=jdbc:oracle:thin:@127.0.0.1:1521:dbname1
 5 Cp_Db_User=user1
 6 Cp_Db_Password=psw1
 7 Cp_Db_Driver=oracle.jdbc.OracleDriver
 8 #his数据库连接串
 9 His_Db_ConnString=jdbc:jtds:sqlserver://127.0.0.2;databaseName=dbname2
10 His_Db_User=user2
11 His_Db_Password=psw2
12 His_Db_Driver=net.sourceforge.jtds.jdbc.Driver
13 #Emr数据库连接串
14 Emr_Db_ConnString=jdbc:oracle:thin:@127.0.0.3:1521:dbname3
15 Emr_Db_User=user3
16 Emr_Db_Password=psw3
17 Emr_Db_Driver=oracle.jdbc.OracleDriver

#红色部分为可自定义部分;蓝色部分为固定写法

调用样例

//查询his信息
1
HashMap<String, HashMap<String, Object>> table = CommonFunction.ExecuteQuery(sql, "His");
//插入到临床路径中
2 int x = CommonFunction.ExecuteNonQuery(insertSql, "Cp");
//此处 的His 与Cp即配置文件中所指定的数据库

 

推荐阅读