一、前言
关于oschrenk-util源码包中com.oschrenk.db.Connector、com.oschrenk.db.DatabaseSettings数据连接配置类,通过Class.forName注册数据驱动类,然后使用DriverManager.getConnection创建数据连接,详情参见源码说明。
二、源码说明
1.DatabaseSettings数据库设置接口
package com.oschrenk.db;@b@@b@public abstract interface DatabaseSettings@b@{@b@ public abstract String getURL();@b@@b@ public abstract String getUsername();@b@@b@ public abstract String getPassword();@b@@b@ public abstract String getDriver();@b@}
2.Connector数据库连接类
package com.oschrenk.db;@b@@b@import java.sql.Connection;@b@import java.sql.DriverManager;@b@import java.sql.SQLException;@b@@b@public class Connector@b@{@b@ private DatabaseSettings settings;@b@ private static Connection conn;@b@@b@ private Connector(DatabaseSettings settings)@b@ {@b@ this.settings = settings;@b@ loadDriver();@b@ }@b@@b@ private void loadDriver()@b@ {@b@ try@b@ {@b@ Class.forName(this.settings.getDriver());@b@ } catch (ClassNotFoundException e) {@b@ e.printStackTrace();@b@ }@b@ }@b@@b@ private Connection connect()@b@ throws SQLException@b@ {@b@ return DriverManager.getConnection(this.settings.getURL(), this.settings.getUsername(), this.settings.getPassword());@b@ }@b@@b@ public Connection getConnection()@b@ throws SQLException@b@ {@b@ if (conn == null)@b@ conn = connect();@b@@b@ return conn;@b@ }@b@@b@ public static Connector getInstance(DatabaseSettings settings) {@b@ return new Connector(settings);@b@ }@b@}