日期:2014-05-16 浏览次数:20442 次
java配置数据库连接池以mysql和sqlserver为例
配置tomcat下面的content.xml
?
<!-- The contents of this file will be loaded for each web application --> <Context> <Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/com?useUnicode=true&characterEncoding=UTF-8" username="root" password="root" maxActive="100" maxIdle="2" maxWait="10000" /> <ResourceParams name="jdbc/mysql"> <parameter> <name>removeAbandoned</name> <value>true</value> </parameter> <parameter> <name>removeAbandonedTimeout</name> <value>60</value> </parameter> <parameter> <name>logAbandoned</name> <value>true</value> </parameter> </ResourceParams> <Resource name="jdbc/sqlserver" auth="Container" type="javax.sql.DataSource" driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver" url="jdbc:microsoft:sqlserver://localhost:1433;databaseName=fashion" username="sa" password="" maxActive="100" maxIdle="30" maxWait="10000" /> <ResourceParams name="jdbc/sqlserver"> <parameter> <name>removeAbandoned</name> <value>true</value> </parameter> <parameter> <name>removeAbandonedTimeout</name> <value>60</value> </parameter> <parameter> <name>logAbandoned</name> <value>true</value> </parameter> </ResourceParams>--> <!-- Default set of monitored resources --> <!-- <WatchedResource>WEB-INF/web.xml</WatchedResource>--> <WatchedResource>WEB-INF/web.xml</WatchedResource> <!-- Uncomment this to disable session persistence across Tomcat restarts --> <!-- <Manager pathname="" /> --> <!-- Uncomment this to enable Comet connection tacking (provides events on session expiration as well as webapp lifecycle) --> <!-- <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" /> --> </Context>
?
?设置项目目录下面的WEB-INF下面的web.xml文件?在里面加入
?
<!-- 数据源 --> <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/mysql</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> <resource-ref> <description>DB</description> <res-ref-name>jdbc/sqlserver</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
测试文件
?
<%@ page contentType="text/html;charset=UTF-8" import="com.shop.util.*"%> <%@ page import="java.sql.*"%> <%@ page import="javax.sql.*"%> <%@ page import="javax.naming.*"%> <%@ taglib uri="/struts-tags" prefix="s" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
<% DataSource ds = null; InitialContext ctx=new InitialContext(); ds=(DataSource)ctx.lookup("java:comp/env/jdbc/sqlserver"); Connection conn = ds.getConnection(); %> <% Statement stmt=conn.createStatement(); String sql_gun="sele