Tomcat 貌似有连接池管理的模块,只要配置了数据库相关信息,并告诉web应用程序,web应用程序启动后,就可以从Tomcat那里获取连接。
/*软件配置:windows xp; tomcat7; mysql5.5*/
1.打开apache-tomcat-7\conf\context.xml,加入数据库资源信息:
<Resource name="jdbc/mysource" auth="Container" type="javax.sql.DataSource" password="sikaijian" username="root" driverClassName="org.gjt.mm.mysql.Driver" url="jdbc:mysql://localhost:3306/mybase" maxActive="100" maxIdle="30" maxWait="5000"/>
2. tomcat 需要mysql的驱动程序,所以要再lib目录中加入驱动JAR包,如:mysql-connector-java-5.1.20-bin.jar;
3.要让web应用知道用这么一个数据源,这么一个连接池可以使用,需要在web.xml中加入如下代码:
<resource-ref> <description>MySQL DataSource</description> <res-ref-name>jdbc/mysource</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
完成以上三步,一个数据源就算配置完成了。
下面做了个简单的测试,JSP片段代码如下:
<%
try
{
Context initCtx=new InitialContext();
DataSource ds = (DataSource)initCtx.lookup("java:comp/env/jdbc/mysource");
Connection conn=ds.getConnection();
out.println("data from database:<br>");
Statement stmt=conn.createStatement();
ResultSet rs =stmt.executeQuery("select * from staff");
%><table border="true" bordercolor="black">
<tr>
<td width="50">姓名</td>
</tr>
<%
while(rs.next())
{
%><tr><%
%><td width="50"><%out.println(rs.getString("name"));%></td><%
%></tr><%
}
%></table><%
rs.close();
stmt.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
/*
mysql创建数据库的时候,可以设置字符编码。创建表的时候也可以设置字符编码。
*/
本文介绍了如何在Windows XP环境下,通过配置Apache Tomcat 7和MySQL 5.5,实现数据库连接池的管理。详细说明了在context.xml文件中加入数据库资源信息、在lib目录中添加MySQL驱动程序JAR包,以及在web.xml中配置数据源的过程。并通过JSP代码展示了如何使用配置好的数据源进行数据库操作。
127

被折叠的 条评论
为什么被折叠?



