Tomcat下的web项目通过数据源连接mysq数据库

本文介绍了如何在Tomcat服务器中配置数据源以连接MySQL数据库。首先在server.xml或context.xml中定义Resource,接着在web项目的web.xml中声明resource-ref,然后确保MySQL驱动在Tomcat的lib目录或项目lib下,最后在代码中使用指定方式获取数据库连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1  在<CATALINA_HOME></conf>server.xml文件中的相应<Host>元素中配置<Resource>子元素(或者在<CATALINA_HOME></conf>context.xml文件中配置也可


2  在web项目的WEB-INF/web.xml文件中加入<resource-ref>元素


3  将mysql驱动包复制到<CATALINA_HOME>/lib目录(或者 项目的WEB-INF/lib目录


4  在程序中通过如下语句获得连接

  Connection con;
  Statement stmt;
  ResultSet rs;
 //建立数据库连接
  Context ctx = new InitialContext();
  DataSource ds =(DataSource)ctx.lookup("java:comp/env/jdbc/BOOKDB");//这里jdbc/BOOKDB为在<Resource>元素中给的命名
  con = ds.getConnection();

5 下面是<Resource>子元素和WEB-INF/web.xml文件源码

<Resource>:

<Resource name="jdbc/BOOKDB" auth="Container" type="javax.sql.DataSource"
     maxActive="100" maxIdle="30" maxWait="10000"
     username="dbuser" password="1234" 
     driverClassName="com.mysql.jdbc.Driver"
     url="jdbc:mysql://localhost:3306/BOOKDB?autoReconnect=true"/> 
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/BOOKDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
  <display-name>bookstore1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值