---
title: "eclipse下tomcat6.0配置mysql数据源"
author: "junherry"
date: "2009-11-16T23:37:31Z"
tags: []
slug: "eclipse-tomcat6-0-mysql"
draft: false
lastmod: "2009-11-17T14:11:38Z"
id: 518539
url: "https://junherry.iteye.com/blog/518539"
---

[链接http://junherry.iteye.com/admin/blogs/518539](/admin/blogs/518539 "http://junherry.iteye.com/admin/blogs/518539")

 

在eclipse中，我们配置好tomcat服务器后，在左侧的项目一览表中会出现server的信息，连接数据源，需要我们更改里面的三个配置文件。假设我们在mysql中建了一个名为cms的数据库，我们把数据源的名字叫做jdbc/mysql。

 

首先是服务器上下文配置信息context.xml，在这里我们要在其元素&lt;context&gt;&lt;/context&gt;内添加数据源的配置信息：

```
<Resource name="jdbc/mysql" driverClassName="com.mysql.jdbc.Driver" maxActive="10" maxIdle="2" maxWait="300" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/cms?autoReconnect=true" username="root" password="admin" validationQuery="select * from student"/>
```

然后是server.xml. 在这里我们要在其元素&lt;GlobalNamingResources&gt;&lt;GlobalNamingResources&gt;内添加数据源的配置信息：

```
<Resource name="jdbc/mysql" driverClassName="com.mysql.jdbc.Driver" maxActive="10" maxIdle="2" maxWait="300" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/cms?autoReconnect=true" username="root" password="admin" validationQuery="select * from student"/>
```

 

然后，再更改web.xml中的配置信息，在其元素&lt;web-app&gt;&lt;/web-app&gt;中添加下面的信息：

```
<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> 
```

我们可以写一个servlet，在其中测试一下数据源是否连通。

```
    Context ctx = null;  
    DataSource ds = null;  
    Connection conn = null;  
    Statement stmt = null;  
    ResultSet rs = null;  
   
    try {  
        ctx = new InitialContext();  
        if (ctx == null){
              out.println("no context"); 
              return;
        } 
        ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mysql");  
        if (ds != null)
        conn = ds.getConnection();  
        stmt = conn.createStatement();  
        String strSql = "select * from student";  
        rs = stmt.executeQuery(strSql);  
         while (rs.next()) {  
             out.println(rs.getString(2));  
         }  
     } catch (Exception ex) {  
         ex.printStackTrace();  
         out.println(ex.toString());  
    } finally {  
         try{
             if (rs != null)  rs.close();  
             if (stmt != null) stmt.close();  
             if (conn != null) conn.close();  
             if (ctx != null) ctx.close();  
        }catch(){}
     } 
```