tomcat如何配置数据源
时间: 2023-07-07 17:41:51 浏览: 56
在 Tomcat 中配置数据源,可以使用 Tomcat 的内置数据源(JNDI DataSource)或者第三方的数据源,例如 Apache Commons DBCP 或者 C3P0 等。
下面是使用 Tomcat 内置数据源配置数据源的步骤:
1. 在 Tomcat 的 conf 目录下的 context.xml 文件中添加如下配置:
```xml
<Resource name="jdbc/MyDataSource" auth="Container"
type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydatabase"
username="dbuser" password="dbpassword"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"/>
```
其中,name 属性指定数据源的 JNDI 名称,url 属性指定数据库的连接地址,username 和 password 属性指定数据库的登录用户名和密码,maxTotal、maxIdle 和 maxWaitMillis 属性指定连接池的属性。
2. 在 web.xml 文件中添加如下配置:
```xml
<resource-ref>
<description>My DataSource</description>
<res-ref-name>jdbc/MyDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
```
其中,res-ref-name 属性指定数据源的 JNDI 名称,res-type 属性指定数据源的类型,res-auth 属性指定认证方式。
3. 在 Java 代码中获取数据源并使用:
```java
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/MyDataSource");
Connection conn = ds.getConnection();
// 使用连接执行 SQL 查询等操作
conn.close();
```
以上就是使用 Tomcat 内置数据源配置数据源的完整步骤。