java读取xml,获取conn对象

package cn.com.burgeon.util;

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;

public class ConnUtil {

 private static ConnUtil cu = null;

 public static ConnUtil getConnUtil() {
  if (cu == null) {
   cu = new ConnUtil();
  }
  return cu;
 }

 Logger logger = Logger.getLogger(ConnUtil.class.getName());

 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 {

   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;
 }

 /*
  * 读取连接数据库的配置文件 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();

  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;
 }

}

转载于:https://my.oschina.net/u/866563/blog/103697

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值