您的位置:首页 > 运维架构 > Tomcat

使用Tomcat数据源访问MySQL数据库

2011-05-05 11:45 302 查看
使用Tomcat作为Web服务器,Tomcat中可以配置一个数据源,然后只要使用JNDI(The Java Naming and Directory Interface)访问该数据源即可访问数据库。

使用JNDI访问数据库的好处是开发者不用关心数据库的相关配置,数据库的配置由应用服务器来管理,大部分应用服务器都提高了数据库连接池的功能,可以极大的提高数据库的访问效率。

在Tomcat中配置数据源,需要在Tomcat(Tomcat 6.0版本)安装目录下的/conf/context.xml配置文件中增加如下配置:
<Context useNaming="true">
<!-- Default set of monitored resources -->
<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" />
-->

<Resource name="jdbc/bookOnline" auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="1226"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/bookOnline" />

<Resource name="jdbc/bbsdb" auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="1226"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/bbsdb" />

</Context>

同时在Web应用的web.xml文件中增加上述的数据源引用,这样该Web应用就可以使用Tomcat配置的数据源了,其增加的内容如下:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/bookOnline</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

使用数据源连接的代码:

private static DataSource ds=null;
private static Connection con=null;
public static Connection getCon_dataSource(){
try{
InitialContext ctx=new InitialContext();
//该处的数据库bookOnline是前文数据源配置里的数据库
ds=(DataSource)ctx.lookup("java:comp/env/jdbc/bookOnline");
con=ds.getConnection();
return con;
}
catch(Exception e){
System.out.println("数据库连接异常:"+e.getMessage());
return null;
}
}

//关闭数据库连接
public void closeCon(){
try{
con.close();
}
catch(Exception e){
System.out.println("数据库连接关闭异常:"+e.getMessage());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: