以前一直都是通过在JavaBean中建立JDBC 连接,使用完成后即断开的方式操作数据库,感觉这种方式造成了很多不必要的开销,尤其遇到需要经常建立、断开连接的情况。还有就是具体部署的时候也不是很方便。所以决定尝试一下数据源的方式,折腾了一上午,还好总算搞定,可以安心吃饭了,先记下来,以备日后查看。
1. 建立数据库,并插入几条测试数据。
CREATE TABLE `usertable` (
`UserName` char(20) NOT NULL default ',
`Password` char(20) default NULL,
PRIMARY KEY (`UserName`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data for the table `usertable` */
insert into `usertable` values ('liang','pwd'),('test1','pwd'),('test2','pwd');
2. 通过tomcat的admin操作界面即 http://localhost:8080/admin 配置数据源.
JNDI Name: jdbc/testdb
Data Source URL: jdbc:mysql://localhost/testdb?useUnicode=true&characterEncoding=GBK
User Name: root
Password: ****
Max.ActiveConnections: 4
Max.IdleConnection: 2
Max.WaitforConnection: 5000
3. 在D:/Tomcat/conf/Catalina/localhost下添加对应工程的配置文件TEST.xml内容为:
<?xml version='1.0' encoding='utf-8'?>
<Context workDir="work/Catalina/localhost/TEST" path="/TEST" docBase="D:/Tomcat/webapps/TEST">
<Resource type="javax.sql.DataSource" auth="Container" name="jdbc/testdb"/>
<ResourceParams name="jdbc/testdb">
<parameter>
<name>maxWait</name>
<value>5000</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>4</value>
</parameter>
<parameter>
<name>password</name>
<value>root</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:mysql://127.0.0.1/testdb?useUnicode=true&characterEncoding=GBK</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>2</value>
</parameter>
<parameter>
<name>username</name>
<value>root</value>
</parameter>
</ResourceParams>
</Context>
4. D:/Tomcat/webapps/TEST/WEB-INF/web.xml文件</web-app>前添加:
<resource-ref>
<res-ref-name>jdbc/testdb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
几个需要注意的地方:
1. 将mysql的JDBC驱动程序拷贝到D:/Tomcat/common/lib目录下
2. 重启Tomcat服务器。
用文件testDataSource.jsp测试:
<%@ page language="java" import="java.util.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.naming.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
out.println(basePath);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
This is my JSP page. <br>
<%
Context ctx=null;
Connection cnn=null;
java.sql.Statement stmt=null;
ResultSet rs=null;
try
{
ctx=new InitialContext();
if(ctx==null)
throw new Exception("initialize the Context failed") ;
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/testdb") ;
out.println(ds);
if(ds==null)
throw new Exception("datasource is null") ;
try{
cnn=ds.getConnection();
out.println("<br> connection:"+cnn);
stmt = cnn.createStatement();
rs = stmt.executeQuery("SELECT * FROM usertable") ;
while (rs.next()){
out.println("<br>") ;
out.println(rs.getString("UserName") );
}
}catch(Exception e){
e.printStackTrace();
}
}
finally
{
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(cnn!=null)
cnn.close();
if(ctx!=null)
ctx.close();
}
%>
1. 建立数据库,并插入几条测试数据。
CREATE TABLE `usertable` (
`UserName` char(20) NOT NULL default ',
`Password` char(20) default NULL,
PRIMARY KEY (`UserName`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data for the table `usertable` */
insert into `usertable` values ('liang','pwd'),('test1','pwd'),('test2','pwd');
2. 通过tomcat的admin操作界面即 http://localhost:8080/admin 配置数据源.
JNDI Name: jdbc/testdb
Data Source URL: jdbc:mysql://localhost/testdb?useUnicode=true&characterEncoding=GBK
User Name: root
Password: ****
Max.ActiveConnections: 4
Max.IdleConnection: 2
Max.WaitforConnection: 5000
3. 在D:/Tomcat/conf/Catalina/localhost下添加对应工程的配置文件TEST.xml内容为:
<?xml version='1.0' encoding='utf-8'?>
<Context workDir="work/Catalina/localhost/TEST" path="/TEST" docBase="D:/Tomcat/webapps/TEST">
<Resource type="javax.sql.DataSource" auth="Container" name="jdbc/testdb"/>
<ResourceParams name="jdbc/testdb">
<parameter>
<name>maxWait</name>
<value>5000</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>4</value>
</parameter>
<parameter>
<name>password</name>
<value>root</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:mysql://127.0.0.1/testdb?useUnicode=true&characterEncoding=GBK</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>2</value>
</parameter>
<parameter>
<name>username</name>
<value>root</value>
</parameter>
</ResourceParams>
</Context>
4. D:/Tomcat/webapps/TEST/WEB-INF/web.xml文件</web-app>前添加:
<resource-ref>
<res-ref-name>jdbc/testdb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
几个需要注意的地方:
1. 将mysql的JDBC驱动程序拷贝到D:/Tomcat/common/lib目录下
2. 重启Tomcat服务器。
用文件testDataSource.jsp测试:
<%@ page language="java" import="java.util.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.naming.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
out.println(basePath);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
This is my JSP page. <br>
<%
Context ctx=null;
Connection cnn=null;
java.sql.Statement stmt=null;
ResultSet rs=null;
try
{
ctx=new InitialContext();
if(ctx==null)
throw new Exception("initialize the Context failed") ;
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/testdb") ;
out.println(ds);
if(ds==null)
throw new Exception("datasource is null") ;
try{
cnn=ds.getConnection();
out.println("<br> connection:"+cnn);
stmt = cnn.createStatement();
rs = stmt.executeQuery("SELECT * FROM usertable") ;
while (rs.next()){
out.println("<br>") ;
out.println(rs.getString("UserName") );
}
}catch(Exception e){
e.printStackTrace();
}
}
finally
{
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(cnn!=null)
cnn.close();
if(ctx!=null)
ctx.close();
}
%>