Tomcat 中通过 JNDI 配置访问数据库
null | 阅2968 | 来源:好空间网络 [打印] [关闭] |
1,所需要的jar文件:commons-pool.jar, commons-dbcp.jar
2,server.xml的配置:
3,程序中的调用:
Context ctx = new InitialContext();
if (ctx == null)
throw new Exception("Boom - No Context");
DataSource ds =
(DataSource) ctx.lookup(
"java:comp/env/jdbc/hellohibernate");
if (ds != null) {
Connection conn = ds.getConnection();
if (conn != null) {
foo = "Got Connection " + conn.toString();
Statement stmt = conn.createStatement();
ResultSet rst =
stmt.executeQuery(
"select username,id from user");
if (rst.next()) {
foo = rst.getString(1);
bar = rst.getInt(2);
}
conn.close();
}
}