1 环境描述
JDK 1.5
Tomcat 5.5.4
MySQL 4.0.20
MySQL JDBC 3.0.15
Commons dbcp 1.2.1
2 准备工作
安装JDK, Tomcat, MySQL
从http://dev.mysql.com/downloads/下载mysql-connector-java-3.0.15-ga.zip,将其中的mysql-connector-java-3.0.15-ga-bin.jar放到jre/lib/ext和Tomcat 5.5/common/lib里面。
从http://jakarta.apache.org/commons/dbcp/下载commons-dbcp-1.2.1.zip,将其中的commons-dbcp-1.2.1.jar放到jre/lib/ext和Tomcat 5.5/common/lib里面。
(以上下载的驱动包版本不一定要跟上面一样)
3 配置Tomcat和项目的web.xml文件
在Tomcat 5.5/conf/server.xml的<GlobalNamingResources>中添加:
<Resource name="JDBC for MySQL" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" password="" maxIdle="2" maxWait="5000" username="root" url="jdbc:mysql://localhost/test" maxActive="4"/>。
在Tomcat 5.5/webapps/test/WEB-INF/web.xml(就是需要使用连接池的web项目的web.xml文件)的<web-app>中添加:
<resource-ref>
<description>MySQL Connection Pool</description>
<res-ref-name>JDBC for MySQL</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
在Tomcat 5.5/webapps/test/META-INF/context.xml的<Context>中添加:
<ResourceLink name="JDBC for MySQL" global="JDBC for MySQL" type="javax.sql.DataSourcer"/>
项目中没有context.xml文件的话,也可以不要改这一步
4 测试,在JAVA中使用数据库连接池
第一步: 创建数据库并在tomcat下配置链接池
1.创建数据库
在mysql下创建名为testdb的数据库,在testdb下创建数据表test_table.字段id,name
2.tomcat配置
我们在C:\Program Files\Tomcat 5.5.7\conf\content.xml文件中添加如下数据库链接池配置,如果没有就新建一个content.xml,注意tomcat版本要5.5以上,5.5以下不支持content.xml。
<Context>
<Resource name="jdbc/testdb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/mytestdb"
username="root"
password="******"
maxActive="100"
maxIdle="30"
maxWait="10000"
></Resource>
</Context>
红字的地方要根据实际情况改变,比如数据库名,用户名,密码,如果使用的是其他类型的数据库,驱动名也要改。
第二步:编写javaBean读取tomcat下的content.xml
javaBean 文件DataBase.java代码
package withouttears.bean;
import java.util.HashMap;
import java.sql.*;
//JNDI有两个核心接口Context和DirContext,
//Context中包含了基本的名字操作,而DirContext则将这些操作扩展到目录服务。
import javax.naming.Context;
import javax.naming.InitialContext;
//数据库资源的连接工厂是javax.sql.DataSource对象,
//它可以创建java.sql.Connection数据库连接对象。
import javax.sql.DataSource;
//目前您可以从Java开发者连接(http://java.sun.com/products/jdbc/download.html#rowsetcobundle1_0)
//下载CachedRowSet的实现。下载并解压缩安装文件后,将"rowset.jar"文件放到您的类目录下。
//CachedRowSet在sun.jdbc.rowset包中。
import sun.jdbc.rowset.CachedRowSet;
/** *//**
* <b>类</b>: DataBase<br>
* <b>版本</b>: 1.0.0<br>
* <b>作者</b>: wiThouTTears<br>
* <b>时间</b>: 2006-12-18<br>
* <b>QQ</b>: 314765755<br>
* <b>Email</b>: wiThouT--Tears@163.com<br>
* <b>Blog</b>: http://blog.csdn.net/withouttears/<br>
* <b>功能</b>: 用连接池连接MySql数据库及相关操作<br>
* */
public class Database ...{
/** *//**
* 数据库JNDI名称,默认:jdbc/testdb
* */
private String jndiName="jdbc/testdb";
/** *//**
* 建立连接池
* @param null
* @return DataSource
* */
private DataSource localhost()...{
DataSource ds=null;
//在HashMap中通过get()来获取value,通过put()来插入value,
//ContainsKey()则用来检验对象是否已经存在
HashMap<Object,Object> cachedDs=new HashMap<Object,Object> ();
if(cachedDs.containsKey("ds"))//取出空闲状态的数据库连接
...{
/**//* 在DataSource中事先建立了多个数据库连接,
* 这些数据库连接保存在连接池(Connect Pool)中。
* Java程序访问数据库时,只需要从连接池中取出空闲状态的数据库连接;
* 当程序访问数据库结束,再将数据库连接放回连接池。
* */
ds = (DataSource)cachedDs.get("ds");
}
else
try
...{
/**//*在javax.naming包中提供了Context接口,
* 该接口提供了将对象和名字绑定,以及通过名字检索对象的方法。
* */
Context initCtx = new InitialContext();
//lookup(String name):返回与指定的名字绑定的对象,获得数据库连接工厂
ds = (DataSource)initCtx.lookup("java:comp/env/"+getjndiName());
cachedDs.put("ds", ds);
}
catch(Exception e)
...{
e.printStackTrace();
}
return ds;
}
/** *//**
* 库的连接
* @param null
* @return Connection
* */
public Connection getConnection()...{
Connection conn = null;
try...{
DataSource ds = localhost();
conn = ds.getConnection();
}
catch(Exception e)...{
e.printStackTrace();
}
return conn;
}
/** *//**
* 关闭连接
* @param conn
* @return null
* @since 1.2
* */
public static void close(Connection conn)...{
try...{
if(conn != null)
conn.close();
}
catch(SQLException e)...{
e.printStackTrace();
}
}
/** *//**
* 执行查询操作
* @param sql
* @return ResultSet
* */
public CachedRowSet executeQuery(String sql)
...{
Connection conn=null;
CachedRowSet rs=null;
try...{
rs=new CachedRowSet();
conn=getConnection();
Statement stmt=conn.createStatement();
ResultSet rs1=stmt.executeQuery(sql);
rs.populate(rs1);
}
catch(Exception e) ...{
System.out.println(e.toString());
}
finally...{
try...{
conn.close();
}
catch(Exception ex)...{}
}
return rs;
}
/** *//**
* 执行数据的插入、删除、修改操作
* @param sql
* @return boolean
* */
public boolean executeUpdate(String sql)...{
boolean bl;
bl = false;
Connection conn = getConnection();
try...{
Statement stmt = conn.createStatement();
if(stmt.executeUpdate(sql) > 0)
stmt.close();
bl = true;
}
catch(SQLException e)...{}
finally...{
close(conn);
}
return bl;
}
/** *//**
* 获得数据库JNDI名称
* @param null
* @return String
* */
public String getjndiName()...{
return this.jndiName;
}
/** *//**
* 设置数据库JNDI名称
* @param jndiName
* @return true|false
* */
public boolean setjndiName(String jndiName)...{
this.jndiName = jndiName;
return true;
}
}
第三步: 编写test.jsp测试
<%@page import="withouttears.bean.Database"%>
<%@page import="java.sql.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>Insert title here</title>
</head>
<body>
<%
Database db=new Database();
db.setjndiName("jdbc/testdb");//初始化JNDI名称
ResultSet rs=db.executeQuery("select * from test_table");
while(rs.next())...{
out.println("id:"+rs.getInt("id")+"<br>");
}
rs.close();
%>
</body>
</html>
总结:
其实使用数据库连接池的方法与传统的JDBC的方法大同小异,只不过多了多了几个应用服务器的配置和web.xml文件的配置。
传统的JDBC连接数据库的方法为:
1.先将数据库驱动包.jar文件放入项目lib文件夹
2.在代码中,使用Class.forName(驱动名)的方式加载数据库驱动
3.使用DriverManager.getConnection(url)的方式获得Connection对象。
使用数据库连接池的方法为
1.配置Tomcat的server.xml和content.xml文件,并配置项目WEB-INF目录下的web.xml。
在Tomcat 5.5/conf/server.xml的<GlobalNamingResources>中添加:
<Resource name="JDBC for MySQL" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" password=""
maxIdle="2" maxWait="5000" username="root" url="jdbc:mysql://localhost/test" maxActive="4"/>。
在C:\Program Files\Tomcat 5.5.7\conf\content.xml文件中添加如下数据库链接池配置,如果没有就新建一个content.xml,注意tomcat版本要5.5以上,5.5以下不支持content.xml。
<Context>
<Resource name="jdbc/testdb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/mytestdb"
username="root"
password="******"
maxActive="100"
maxIdle="30"
maxWait="10000"
></Resource>
</Context>
在Tomcat 5.5/webapps/test/WEB-INF/web.xml(就是需要使用连接池的web项目的web.xml文件)的<web-app>中添加:
<resource-ref>
<description>MySQL Connection Pool</description>
<res-ref-name>JDBC for MySQL</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
在Tomcat 5.5/webapps/test/META-INF/context.xml的<Context>中添加:
<ResourceLink name="JDBC for MySQL" global="JDBC for MySQL" type="javax.sql.DataSourcer"/>
项目中没有context.xml文件的话,也可以不要改这一步
2.将驱动包导入tomcat的conf\lib文件夹
3.在代码中 通过 Context context=new InitialContext();获取一个对象context
通过 (DataSource)context.lookup("java:comp/env/XXXX(在tomcat的content.xml文件中配置的Resource name)"); 获取数据源ds
通过 ds.getConnection(); 获取Connection对象。
关于Context DataSource 的详细信息课参考JAVA API文档。