package cn.com.burgeon.util; java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.JDOMException; sql
public class ConnUtil { 數據庫
private static ConnUtil cu = null; apache
public static ConnUtil getConnUtil() {
if (cu == null) {
cu = new ConnUtil();
}
return cu;
} dom
Logger logger = Logger.getLogger(ConnUtil.class.getName()); ui
public Connection getConnection(String xmlDbConf) {
Map<String, String> map = null;
try {
map = getDatasourceXml(xmlDbConf);
} catch (Exception e) {
logger.error("讀取wepos.properties文件失敗\n" + e.getMessage());
}
Connection conn = null;
try { url
Class.forName(map.get("driverclass"));
conn = DriverManager.getConnection(map.get("connectionurl"), map
.get("username"), map.get("password"));
} catch (Exception e) {
logger.error("鏈接數據庫失敗\n" + e.getMessage());
}
return conn;
} xml
/*
* 讀取鏈接數據庫的配置文件 liferay-ds.xml
*/
public static Map<String, String> getDatasourceXml(String xmlFile)
throws JDOMException, IOException {
Map<String, String> map = new HashMap<String, String>();
org.jdom2.input.SAXBuilder sb = new org.jdom2.input.SAXBuilder();
org.jdom2.Document doc = sb.build(new java.io.File(xmlFile)); // 改這個路徑
org.jdom2.Element root = doc.getRootElement(); // 根節點
List<Element> childList = root.getChildren(); get
String connectionurl = childList.get(1).getChildText("connection-url"); // 根節點之下的子節點class_name的內容
String driverclass = childList.get(1).getChildText("driver-class");
String username = childList.get(1).getChildText("user-name") == null ? "neands3"
: childList.get(1).getChildText("user-name");
String password = childList.get(1).getChildText("password") == null ? "abc123"
: childList.get(1).getChildText("password");
map.put("connectionurl", connectionurl);
map.put("driverclass", driverclass);
map.put("username", username);
map.put("password", password);
return map;
} input
}