📄 connpoolhandler.java
字号:
package com.sxit.mms.receive;
import java.io.File;
import java.sql.Connection;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import com.cmcc.mm7.vasp.conf.MM7ConfigManager;
/**
* 通过jndi获取从数据库的连接。相关参数从配置文件获得
*
* @author HuaFeng
* @version 1.0 (2006-2-9 9:42:01)
*
*/
public class ConnPoolHandler {
private final static Logger log = Logger.getLogger(ConnPoolHandler.class);
private String contextFactory;
private String providerURL;
private String jndiName;
private static ConnPoolHandler pool = new ConnPoolHandler();
// private static ConnPoolHandler pool = null;
public static final ConnPoolHandler getInstance() {
if (pool == null)
pool = new ConnPoolHandler();
log.info("数据库连接获取对象初始化成功!");
return pool;
}
private void init() {
try {
// File file = new
// File(this.getClass().getResource("ConnPoolHandler.class").getFile());
// String path = file.getParent();
// Properties properties = new Properties();
// properties.load(new FileInputStream(path +
// "/dbconn.properties"));
File file = new File(this.getClass().getResource("MMReceiveServlet.class").getFile());
String path = file.getParent();
// MM7Config Config = new MM7Config();
MM7ConfigManager mm7c = new MM7ConfigManager();
mm7c.load(path + "/mm7Config.xml");
contextFactory = mm7c.hashmap.get("ContextFactory").toString();
providerURL = mm7c.hashmap.get("ProviderURL").toString();
jndiName = mm7c.hashmap.get("JndiName").toString();
if (log.isDebugEnabled()) {
log.debug("contextFactory=" + contextFactory);
log.debug("providerURL=" + providerURL);
log.debug("jndiName=" + jndiName);
}
}
catch (Exception e) {
contextFactory = "";
providerURL = "";
jndiName = "sxit";
log.error("初始化错误" + e);
}
}
private ConnPoolHandler() {
init();
}
public Connection getConnection() {
try {
Hashtable ht = new Hashtable();
if (contextFactory != null && !"".equals(contextFactory))
ht.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
if (providerURL != null && !"".equals(providerURL))
ht.put(Context.PROVIDER_URL, providerURL);
Context ctx = new InitialContext(ht);
DataSource ds = (DataSource) ctx.lookup(jndiName);
Connection con = ds.getConnection();
return con;
}
catch (Exception e) {
log.error("获取数据库连接错误:" + e);
return null;
}
}
public void closeConnection(Connection con) {
try {
if (con != null)
con.close();
if (log.isDebugEnabled()) {
log.debug("数据库连接关闭,con.isClosed()=" + con.isClosed());
}
}
catch (Exception e) {
log.error("数据库连接关闭有误:" + e);
}
}
// public static void main(String args[]) {
// ConnPoolHandler pool = new ConnPoolHandler();
// System.out.println(pool.contextFactory);
// System.out.println(pool.jndiName);
// System.out.println(pool.providerURL);
// }
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -