<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<!--
数据库地址
-->
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost/test?useUnicode=true</value>
</parameter>
</ResourceParams>
</Context>
设置好连接池,我们对连接池进行测试
我们编写一个Servlet测试在Servlet使用连接池
代码如下
package com.test.web;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
/**
* @author yanghx
* To change the template for this generated type comment go to Window -
* Preferences - Java - Code Generation - Code and Comments
*/
public class TestServlet extends HttpServlet {
private static Logger log = Logger.getLogger(TestServlet.class);
public void init() throws ServletException {
super.init();
String jndiName = "java:comp/env/jdbc/mysql";
try {
Context ctx = new InitialContext();
if (ctx == null) {
log.error("找不到上下文");
throw new Exception("找不到上下文");
}
DataSource ds = (DataSource) ctx.lookup(jndiName);
Connection conn = ds.getConnection();
PreparedStatement psmt = conn
.prepareStatement("select * from tbl_testhbm");
ResultSet rs = psmt.executeQuery();
log.info("连接池OK");
rs.close();
} catch (NamingException e) {
log.error("找不到上下文" + e.getMessage());
} catch (Exception e) {
log.error("出现错误" + e.getMessage());
}
}
}
本文地址:http://com.8s8s.com/it/it16698.htm