转自:http://qzxfl008.iteye.com/blog/791819
这几天,老师要让我负责数据库连接池,之前配置的连接池是在tomcat6.x中,是全局的,但老师要求我们要局部的,这样方便将来修改容易。
网上查资料查了很多,现在整理下。我的是在tomcat6.x中配置的1、配置 context.xml文件将,放在工程的META-INF目录下,注意不是在WEB-INF下。 ps:目录千万别放错,正式因为我放错目录导致我浪费N长时间来处理问题
Cannot create JDBC driver of class '' for connect URL 'null'
其中<context 里的path等可以有,也可以无
- <Context
- path="/spp" docBase="spp"
- debug="5" reloadable="true" crossContext="true" >
- <Resource name="jdbc/mysqlds"
- auth="Container"
- type="javax.sql.DataSource"
- driverClassName="com.mysql.jdbc.Driver"
- url="jdbc:mysql://localhost:3306/spms?autoReconnect=true"
- username="root"
- password=""
- maxActive="100"
- maxIdle="30"
- maxWait="10000"
- />
- </Context>
2、在WEB-INF下的web.xml中添加如下代码,这段可有可无
- <resource-ref>
- <description>MySQL DataSource</description>
- <res-ref-name>jdbc/mysqlds</res-ref-name>
- <res-type>javax.sql.DataSource</res-type>
- <res-auth>Container</res-auth>
- </resource-ref>
3、不要忘了加驱动jar包mysql-connector-java-5.1.12-bin.jar
放在WebRoot/WEB-INF/lib/下
4、测试代码
- <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%>
- <%@ page import="java.sql.*" %>
- <%@ page import="javax.naming.*" %>
- <%@ page import="javax.sql.DataSource" %>
- <%
- try
- {
- //初始化Context
- Context initCtx = new InitialContext();
- System.out.println(initCtx);
- Context envCtx = (Context)initCtx.lookup("java:comp/env");
- System.out.println(envCtx);
- DataSource ds = (DataSource)envCtx.lookup("jdbc/mysqlds");
- System.out.println(ds);
- Connection conn = ds.getConnection();
- Statement stmt = conn.createStatement();
- //获取服务器端时间,适用于MySQL(还有current_time(),current_date()等)
- //MS SQLServer为getDate()
- String strSQL = "select current_timestamp()";
- ResultSet rs = stmt.executeQuery(strSQL);
- rs.next();
- Timestamp date = rs.getTimestamp(1);
- out.print(date.toString());
- rs.close();
- stmt.close();
- conn.close();
- }catch(Exception e)
- {
- out.print("错误"+e.getMessage());
- }
- %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
- <title>test</title>
- </head>
- <body>
- </body>
- </html>