java 数据库连接方式(六)

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;
			} else
				dbType = 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();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值