一个基本成熟的数据库连接池(part 1)

2014-11-23 22:09:52 · 作者: · 浏览: 0

最近,本人着手开发要有一个有强大后台的网站,在使用连接池时,觉得使用服务器自带的连接池总有些受限制。同时,为了加深对Java的学习和研究。写下了下面的连接池类。
该连接池主要有一下功能;

1)初始化一次,到处使用。
2)强大的日志功能,记录每一个sql动作,包括Connection、ResultSet 和Statement
3)根据连接的数量,定时自动回收已经释放或超时的连接。
4)配置灵活,可以使用各种JDBC驱动程序,支持多驱动程序。

更新说明:

1)新增了字符集配置项。
2) 新增了调试开关,便于使用前调试。
3)更改了日志日期输出格式。
4)排除了createStatement l里的一个bug (感谢rouselion的使用反馈)
5)修正了被封装类的getXXX函数的潜在的问题。

源代码:

  1. //file : *****< ConnectionManager.java >****
  2. /*
  3. * @Title 连接池
  4. * @Author: zxg
  5. * @Version 2.5
  6. * @Memo:定义数据库连接及其数据库连接池等
  7. */
  8. package com.dbaccess.dbpool;
  9. import java.io.*;
  10. import java.sql.*;
  11. import java.util.*;
  12. import com.mysql.jdbc.Driver;
  13. public class ConnectionManager {
  14. static private ConnectionManager instance; // 唯一实例
  15. // static private int clients;
  16. static private long checkperiod=0;
  17. private Vector drivers = new Vector();
  18. private Hashtable pools = new Hashtable();
  19. private Timer checkConnTimer=new Timer();
  20. //调试模式开关
  21. private static boolean debug=false;
  22. //字符集哈西表
  23. static private Hashtable Characters= new Hashtable();
  24. static private PrintWriter log;
  25. /**
  26. * 返回唯一实例.如果是第一次调用此方法,则创建实例
  27. *
  28. * @return ConnectionManager 唯一实例
  29. */
  30. static synchronized public ConnectionManager getInstance() {
  31. if (instance == null) {
  32. instance = new ConnectionManager();
  33. }
  34. // clients++;
  35. return instance;
  36. }
  37. /**
  38. * 建构函数私有以防止其它对象创建本类实例
  39. */
  40. private ConnectionManager() {
  41. init();
  42. }
  43. /**
  44. * 读取属性完成初始化
  45. */
  46. private void init() {
  47. Properties dbProps=null;
  48. try {
  49. InputStream is = getClass().getResourceAsStream("db.properties");
  50. dbProps = new Properties();
  51. dbProps.load(is);
  52. }
  53. catch (Exception e) {
  54. e.printStackTrace();
  55. System.err.println("不能读取属性文件= " +
  56. "请确保db.properties在CLASSPATH指定的路径中");
  57. return;