这几天在学习在jsp中使用连接池连接数据库,毕竟以前没有使用过这种方法,感觉它有点新鲜,就把我的学习过程写下来吧。
在mysql数据库中,使用连接池可以有几种方法实现,在使用tomcat进行配置时,方法比较简便,只需要配置好三个xml文件,就可以方便的使用了。而直接使用普通的java类来实现,就有点复杂了,但值得我们好好学习的!
(一)在tomcat中配置
前提:要有mysql的mysql-connector-java-5.0.8-bin.jar包,把它放在%tomcat_HOME%/lib目录下面。
1. 需要配置的三个文件:
(1).%tomcat_home%/conf/server.xml。
在<GlobalNamingResources>与</GlobalNamingResources>之间添加如下代码:
<Resource
name="jdbc/myPool" //数据源名称
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
password="123"
maxIdle="2"
maxWait="5000"
username="root"
url="jdbc:mysql://localhost:3306/test?autoReconnect=true"
maxActive="7"/> //最多同时使用的连接数目
(2).%tomcat_home%/conf/web.xml。
在<web-app></web-app>之间添加如下代码:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/myPool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Conntainer</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
(3).%tomcat_home%/conf/context.xml
在<Context></Context>之间添加如下代码:
<ResourceLink
name="jdbc/myPool"
type="javax.sql.DataSource"
global="jdbc/myPool"/>
2.写数据库连接javabean类:
package conn;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/**
*
* @author Administrator
*
*/
public class Result {
Connection conn =null;
Statement stmt = null;
public ResultSet getResult(String sql)
{
ResultSet rs=null;
DataSource ds = null;
try{
InitialContext ctx;
try {
ctx = new InitialContext();
ds=(DataSource)ctx.lookup("java:comp/env/jdbc/myPool");
} catch (NamingException e) {
e.printStackTrace();
}
conn = ds.getConnection();
stmt = conn.createStatement();
rs=stmt.executeQuery(sql);
} catch(SQLException x) {
x.printStackTrace();
}
return rs;
}
/**
* 关闭数据库连接
*/
public void closeConnection()
{
if(stmt!=null)
try {
stmt.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3.编写jsp代码进行测试:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title></title>
<%
out.print("测试开始*********");
Result result=new Result();
String strSql = "select * from admin_msg";
ResultSet rs = result.getResult(strSql);
while(rs.next()){
out.print(rs.getString(5));
}
out.print("========测试结束");
rs.close();
result.closeConnection();
%>
</head>
<body>
</body>
</html>
注意:因为连接的过程中要读取配置文件,所有不能在java工程中进行调试,要在web工程中使用jsp代码来进行测试,否则不能读取刚才完善的配置文件了!,如果一点要在java工程中实现连接池,那么就要使用另一种实现连接池的方法了,用普通的java类来实现!