获取tomcat连接池

来源:互联网 发布:淘宝个人尺码设置在哪 编辑:程序博客网 时间:2024/06/06 02:10

1.  首先在tomcat中安装目录的conf中配置context.xml,把连接数据库的一些参数配置进去,配置如下:

  <Resource            

       name="jdbc/books"

       type="javax.sql.DataSource" 

       maxActive="100" 

       maxIdle="30" 

       maxWait="10000" 

      driverClassName="com.mysql.jdbc.Driver" 

       url="jdbc:mysql://localhost:3306/books" 

       username="root" 

       password="123456" 

         /> 

 2.    配置web.xml,把数据库连接池引用到项目中:

         <resource-ref> 

               <res-ref-name>jdbc/books</res-ref-name> 

               <res-type>javax.sql.DataSource</res-type> 

               <res-auth>Container</res-auth> 

          </resource-ref> 

 3.    在数据库操作类中获取连接池的连接:

         Context context = new InitialContext(); 

         DataSource dataSource = (DataSource)context.lookup("java:comp/env/jdbc/books"); 

         Connection con =dataSource.getConnection();