chenjiepengc
2013-01-05 13:14:44
java jdbc连接工具类DBConnectionManager
/** * 管理类DBConnectionManager支持对一个或多个由属性文件定义的数据库连接 * 池的访问.客户程序可以调用getInstance()方法访问本类的唯一实例. */ public class DBConnectionManager { static private DBConnectionManager instance; static private int clients; private Vector drivers = new Vector(); private PrintWriter log; private Hashtable pools = new Hashtable(); /** * 返回唯一实例.如果是第一次调用此方法,则创建实例 * @return DBConnectionManager 唯一实例 */ static synchronized public DBConnectionManager getInstance() { if (instance == null) { instance = new DBConnectionManager(); } clients++; return instance; } /** * 建构函数私有以防止其它对象创建本类实例 */ private DBConnectionManager() { init(); } /** * 读取属性完成初始化 */ 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", "dbconMgr.log"); try { log = new PrintWriter(new FileWriter(logFile, true), true); } catch (IOException e) { System.err.println("无法打开日志文件: " + logFile); log = new PrintWriter(System.err); } loadDrivers(dbProps); createPools(dbProps); } /** * 装载和注册所有JDBC驱动程序 * @param 参数 : db.properties */ private void loadDrivers(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("成功注册JDBC驱动程序" + driverClassName); } catch (Exception e) { e.printStackTrace(); log("无法注册JDBC驱动程序: " + driverClassName + ", 错误: " + e); } } }
由AXIN编辑于2014-2-12 16:36:05
猜你喜欢
请下载代码后再发表评论


s569891514 LV2
2018年1月10日
AXIN LV36
2014年2月12日

cccccc1235
2024年5月20日
暂无贡献等级
y1214435276 LV9
2024年4月11日
xianyu091012 LV5
2023年7月19日
胡明杨
2023年4月22日
暂无贡献等级
不正经的90后程序猿 LV1
2022年12月24日
李海洋 LV12
2022年8月7日
17798830 LV14
2022年1月27日
15368725041
2021年8月13日
暂无贡献等级
qaplbgh
2021年6月15日
暂无贡献等级
CoderMars LV13
2021年6月13日