Tomcat数据源连接多个数据库配置

首先找到.....\Apache Software Foundation \Apache Tomcat 7.0.6\conf\server.xml或者.....\Apache Software Foundation\Apache Tomcat 7.0.6\conf\Catalina\localhost\javaMail.xml 根据你部署的项目确定

<!--Two source one connect QQDB and another connect mailDB-->
<Context path="/QQMail" reloadable="true" docBase="E:\PC Language\Java EE\QQMail" workDir="E:\PC Language\Java EE\QQMail\work" >

<!--The first dataSource, connect QQDB -->
<Resource name="jdbc/QQ"
auth
="Container"
type
="javax.sql.DataSource"
maxActive
="100"
maxIdle
="30"
maxWait
="10000"
username
="root"
password
="ligx"
driverClassName
="org.gjt.mm.mysql.Driver"
url
="jdbc:mysql://localhost:3306/QQ" />
<Logger className="org.apache.catalina.logger.SystemOutLogger" verbosity="4" timestamp="true"/>

<!--The second dataSource, connect MailDB-->
<Resource name="jdbc/mail"
auth
="Container"
type
="javax.sql.DataSource"
maxActive
="100"
maxIdle
="30"
maxWait
="10000"
username
="root"
password
="ligx"
driverClassName
="org.gjt.mm.mysql.Driver"
url
="jdbc:mysql://localhost:3306/mail" />
<Logger className="org.apache.catalina.logger.SystemOutLogger" verbosity="4" timestamp="true"/>
</Context> <!--QQMail end of-->



然后在你的项目web.xml里完成以下配置:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/QQ</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/mail</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>


最后测试一下:连接mail的数据库

    Context ctx=new InitialContext();
if(ctx==null){
throw new Exception("No Context");
}
DataSource ds=(DataSource) ctx.lookup("java:comp/env/jdbc/mail");
if(ds!=null){
conn=ds.getConnection();
System.out.println("MailServerDB 连接成功!");
}

连接QQ的数据库:

// 初始化上下文
Context ctx = new InitialContext();
if (ctx == null) {
throw new Exception("No Context");
}
//参照web.xml配置
// 取得连接池
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/QQ");
System.out.println("连接成功!");
if (ds != null) {// 连接池成功取得
// 取得连接池中的连接
conn = ds.getConnection();
}

最后成功完成配置信息,就这样完成基本的配置!三个以上直接添加!Goodluck!!!!!!!!!!!!!!!!!!!!!!


posted @ 2011-09-26 11:51  java_li  阅读(1500)  评论(0编辑  收藏  举报