您的位置:首页 > 编程语言 > Java开发

java 数据库连接方式(六)

2011-07-30 22:37 429 查看
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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: