jndi技术:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 写 jndi的代码
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// 拿到 jndi上下文 对象
Context context = new InitialContext();
Context envCtx = (Context) context.lookup("java:comp/env");
// 获得数据库连接池 象
DataSource ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB");
conn=ds.getConnection();
stmt = conn.prepareStatement("select * from account");
rs = stmt.executeQuery();
while(rs.next()){
String name = rs.getString("name");
String money = rs.getString("money");
System.out.println( " name : " + name +", money : " + money);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JdbcUtils.release(rs, stmt, conn);
}
}
Context.xml:
放在WETA-INFO目录下
<Context>
<Resource name="jdbc/EmployeeDB"
type="javax.sql.DataSource"
username="root"
password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql:///day13"
/>
</Context>