tomcat中c3p0配置(JNDI)

来源:互联网 发布:vmware mac版下载 编辑:程序博客网 时间:2024/04/30 03:59
 (注:一定要将c3p0的三个包考到tomcat的lib目录下面)

1>\Tomcat 5.5\conf\server.xml

2>\Tomcat 5.5\conf\context.xml

3>项目中\WebRoot\WEB-INF\web.xml

配置的代码

1> 在tomcat\conf\server.xml的GlobalNamingResources中增加:
<Resource auth="Container"
     description="DB Connection"
     driverClass="com.mysql.jdbc.Driver"
     maxPoolSize="10"
     minPoolSize="2"
     acquireIncrement="2"
     name="jdbc/mysqlDB"
     user="root"
     password="123123"
     factory="org.apache.naming.factory.BeanFactory"
     type="com.mchange.v2.c3p0.ComboPooledDataSource"
     jdbcUrl="jdbc:mysql://localhost:3306/mldn?autoReconnect=true" />

2> 在tomcat\conf\context.xml的Context中增加:  

<ResourceLink name="jdbc/mysqlDB" global="jdbc/mysqlDB" type="javax.sql.DataSource"/>

3> 在web.xml中增加:

<resource-ref>
     <description>DB Connection</description>
     <res-ref-name>jdbc/mysqlDB</res-ref-name>
     <res-type>javax.sql.DataSource</res-type>
     <res-auth>Container</res-auth>
</resource-ref>

(3)jsp测试页面

<%@page language="java" import="java.util.*,java.sql.*,javax.naming.*,javax.sql.*" pageEncoding="GB2312"%>
<%@page import="com.mchange.v2.c3p0.*"%>
<%@page import="java.sql.Connection"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>    
    <title>My JSP 'mysqlTest.jsp' starting page</title>
</head>

<body>
    Mysql数据库测试<br><br><br>
    <%
    Connection conn=null;
      try
{
      InitialContext ctx = new InitialContext();
      DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mysqlDB");
      conn=ds.getConnection();
}
catch(NamingException ex)
{
   ex.printStackTrace();
}

    String sql="select * from user";
PreparedStatement ps=conn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
    while(rs.next())
{
   %>
   字段1:<%=rs.getString(1)%> 字段2:<%=rs.getString(2)%><br>
   <%
}
    if(rs!=null)
    {
        rs.close();
        rs=null;
    }
    if(ps!=null)
    {
        ps.close();
        ps=null;
    }
    if(conn!=null)
    {
        conn.close();
        conn=null;
    }
    %>
</body>
</html>

---------------

测试通过!

原创粉丝点击