Tomcat配置MySql连接池问题

时间:2022-09-19 22:57:02

配置过程如下:

1、修改Tomcat—>conf目录下的context.xml文件

<Context path="/DBTest" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true">

   
    <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="sa" password="123456"     driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/testdb?autoReconnect=true"/>
</Context>

2、将MySql的jdbc驱动放入到Tomcat—>lib目录下

MySql jdbc驱动下载地址:http://dev.mysql.com/downloads/connector/j/

3、在servlet工程的web.xml增加配置

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

4、java应用中如下使用连接池

String sql = "SELECT * FROM deviceinfo WHERE CAMERA_NAME = '" + cameraName + "'";
        try{
            Context initContext = new InitialContext();
            Context envContext  = (Context)initContext.lookup("java:/comp/env");
            DataSource ds = (DataSource)envContext.lookup("jdbc/TestDB");
            Connection conn = ds.getConnection();
            Statement st = null;
            ResultSet rs = null;
            st = conn.createStatement();
            rs = st.executeQuery(sql);
            rs.next();
            String cameraID = rs.getString("CAMERA_ID");
            rs.close();
            conn.close();
            PrintWriter out = response.getWriter();
            out.print("cameraID = " + cameraID);
        }catch(Exception e){
            
        }

备注:

1、直接在Tomcat安装目录下修改context.xml文件后,通过Eclipse启动Tomcat,会发现context.xml被重置了

解决:若使用Eclipse启动Tomcat,则需要在Eclipse中修改Tomcat的配置文件,如图

 Tomcat配置MySql连接池问题