1.配置tomcat中conf目录下的context.xml文件
<Resource name = "jdbc/ds"
auth = "Container"
type = "javax.sql.DataSource"
maxActive = "100"
maxIdle = "30"
maxWait = "10000"
username = "sa"
password = "123456a"
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
url = "jdbc:sqlserver://localhost:1433;databaseName=QQDB;"
/>
2.得到数据源
javax.naming.Context ctx = null;
DataSource ds = null;
try {
ctx = new javax.naming.InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/ds");
System.out.println("数据源:"+ds);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
3.注意:由于JNDI数据源是由web容器驱动的,所以要将 数据库驱动Copy到tomcat中的lib目录下,
并且只能在web页面下访问才有效,不能进行局部测试(有待改进)
测试JNDI配置数据库连接池(Action)
package com.wang.owbHome.web.action;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.jstl.sql.Result;
import javax.sql.DataSource;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.wang.owbHome.business.util.DB;
public class TestDataSourceAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//TODO 测试数据连接池代码
javax.naming.Context ctx = null;
DataSource ds = null;
try {
ctx = new javax.naming.InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/ds");
System.out.println("数据源:"+ds);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection conn = ds.getConnection();
DB db = new DB();
db.setConnection(conn);
String sql1 = "select * from QQUser";
db.setSqlValues(sql1);
try {
Result rs = db.executeQuery();
if(rs == null || rs.getRowCount() == 0){
System.out.println("没有结果");
}else{
System.out.println("共有" + rs.getRowCount() +"个结果!");
}
db.closeConn();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ni");
return mapping.findForward("success");
}
}