天天看点

配置Tomcat连接池步骤

    Tomcat 貌似有连接池管理的模块,只要配置了数据库相关信息,并告诉web应用程序,web应用程序启动后,就可以从Tomcat那里获取连接。

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  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();
	}
%>