`
junherry
  • 浏览: 95902 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

eclipse下tomcat6.0配置mysql数据源

    博客分类:
  • Java
阅读更多

链接http://junherry.iteye.com/admin/blogs/518539

 

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

 

首先是服务器上下文配置信息context.xml,在这里我们要在其元素<context></context>内添加数据源的配置信息:

<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. 在这里我们要在其元素<GlobalNamingResources><GlobalNamingResources>内添加数据源的配置信息:

<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中的配置信息,在其元素<web-app></web-app>中添加下面的信息:

<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(){}
     } 
 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics