中易网

哪位java大神帮我解释下面一段代码

答案:1  悬赏:70  
解决时间 2021-01-17 03:17
  • 提问者网友:雾里闻花香
  • 2021-01-16 23:34
哪位java大神帮我解释下面一段代码
最佳答案
  • 二级知识专家网友:归鹤鸣
  • 2021-01-16 23:48
public Connection getConnection() {

try {
//读取配置文件,取数据源名称
DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
DocumentBuilder dombuilder = domfac.newDocumentBuilder();
// File f = new File(this.getClass().getResource("/").getPath());
// f = new File(f.getPath() + "/org/ecms/config/db_config.xml");
// InputStream is = new FileInputStream(f);

InputStream is = DBConnection.class.getClassLoader().getResourceAsStream("org/ecms/config/db_config.xml"); //读取org/ecms/config/目录下的db_config.xml文件

Document doc = dombuilder.parse(is);
Element root = doc.getDocumentElement();//获取XML下的所有节点
String resourceName = ((Element)doc.getElementsByTagName("databases").item(0)).getElementsByTagName("resource").item(0).getFirstChild().getNodeValue();
System.out.println(resourceName);
Connection conn = null;
try {
Context initContext = new InitialContext();

//TOMCAT
Context envContext = (Context)initContext.lookup("java:/comp/env");
//假如你需要获取datasource,例如:dataSource = (DataSource) context.lookup("java:comp/env/jdbc/demoDS");
//那么在配置文件中进行资源映射时,在web.xml中,
//
// jdbc/demoDS
//javax.sql.DataSource
//Container
//

DataSource ds = (DataSource)envContext.lookup(resourceName);
//WEBSPHERE
// InitialContext ctx = new InitialContext();
// DataSource ds = (DataSource)ctx.lookup(resourceName);

conn = ds.getConnection();//得到数据库链接
conn.setAutoCommit(false);//设置执行SQL手动提交
initContext.close();

} catch (Exception e) {
e.printStackTrace();
}
return conn;
} catch (Exception e) {
e.printStackTrace();
System.out.println("连接失败");
// TODO: handle exception
}
return conn;//返回拿到的数据库链接
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息