通过JNDI获取数据源,需要如下步骤:
1.首先需要在C:\apache-tomcat-6.0.32\conf目录下的context.xml中加入如下配置:
<Resource
name="jdbc/hao"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:XE"
username="
system"
password="redhat"
maxActive="20"
maxIdle="2"
maxWait="-1"/>
然后启动tomcat。
2.在程序中加入如下代码即可:
DataSource ds = null;
Connection conn = null;
Context initCtx;
try {
initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
ds = (DataSource) envCtx.lookup("jdbc/hao");
conn = ds.getConnection();
Statement stmt = conn.createStatement();
String strSql = " select * from ic_user";
ResultSet rs = stmt.executeQuery(strSql);
while (rs.next()) {
System.out.println(rs.getString("username"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}