java 数据库连接方式(六)

来源:互联网 发布:军工行业 云计算 编辑:程序博客网 时间:2024/06/08 07:15
import com.xxx.config.ConfigManager;import com.xxx.config.Configs;/** * 连接管理类 * @author  */public class ConnectionManager {//数据库类型private static int dbType = -1;private static ConnectionFactory _connFactory;/** * oracle数据库类型标志位 */public static int ORACLE = 1;/** * Mysql数据库类型标志位 */public static int MYSQL = 2;/** * 得到数据库类型 * @return 数据库类型标志位 */public static int getDBType() {if (dbType == -1) {String type = ConfigManager.getKey(ConfigKeys.dbTypeKey);if ("oracle".equals(type)) {dbType = ORACLE;} else if ("mysql".equals(type)){dbType = MYSQL;} elsedbType = 0;}return dbType;}/** * 根据指定的数据库配置得到ConnectionFactory对象。 * @return ConnectionFactory对象 */public static ConnectionFactory getConnectionFactory(Configs conf) {ConnectionFactory fac = null;String type = conf.getConfig(ConfigKeys.dbConnTypeKey);if ("jndi".equals(type)) {fac = new JndiConnectionFactory();} else { String cls = conf.getConfig(ConfigKeys.dbConnClassKey); if (cls == null || cls.length() == 0) { cls = SimpleConnectionFactory.class.getName(); } ClassLoader cl = ConnectionManager.class.getClassLoader();     try {     fac = (ConnectionFactory) cl.loadClass(cls).newInstance();     } catch (Exception ex) {         ex.printStackTrace();         fac = new SimpleConnectionFactory();     }}fac.init(conf);return fac;}/** * 根据默认的数据库配置得到ConnectionFactory对象,数据库操作的入口。默认实现类SimpleConnectionFactory * @return ConnectionFactory对象 */public synchronized static ConnectionFactory getConnectionFactory() {if (_connFactory == null) {Configs conf = ConfigManager.getDefaultConfigs();    _connFactory = getConnectionFactory(conf);}return _connFactory;}static Class connectionClass;static ConnectionObject newConnectionObject() {if (connectionClass == null) { String cls = ConfigManager.getDefaultConfigs().getConfig("ConnectionObjectClassName"); if (cls != null && cls.length() > 0) { ClassLoader cl = ConnectionManager.class.getClassLoader();     try {     connectionClass = cl.loadClass(cls);     } catch (Exception ex) {     } } if (connectionClass == null) { connectionClass = ConnectionObject.class; return new ConnectionObject(); }}try {return (ConnectionObject) connectionClass.newInstance();}catch(Exception ex){}return new ConnectionObject();}}