tomcat 中配置和使用连接池

tomcat 连接池的配置步骤如下
  (1) 将JDBC驱动jar 复制到tomcat_home/common/lib目录下,已便容器能够找到JDBC包。
  (2) 配置 tomcat_home/conf/context.xml,在context.xml文件中的<Context></Context>标签中添加如下内容:
  

     <Resource name="jdbc/my"      
              auth="Container" type="javax.sql.DataSource" 
              driverClassName="com.mysql.jdbc.Driver" 
              maxIdle="1" 
              maxWait="10000" 
              username="root" 
              password="develop" 
              url="jdbc:mysql://192.168.0.192:3306/uc"      
              maxActive="2"  
              removeAbandoned="true" 
              removeAbandonedTimeout="60" 
              logAbandoned="true"/>

  (3) 项目中找到web.xml文件。加入
      <resource-ref>
        <description>DB Connection</description>
        <res-ref-name>jdbc/my</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

  (4) 使用,建立连接
  
public static volatile DataSource ds = null;
    public final static String DATA_SOURCE_NAME = "jdbc/my";
Context initContext;
        try {
            initContext = new InitialContext();

            Context envContext = (Context) initContext.lookup("java:/comp/env");

            ds = (DataSource) envContext.lookup(DATA_SOURCE_NAME);
                        con=ds.getConnection();
           
        } catch (NamingException e) {
            e.printStackTrace();
            throw new RuntimeException("查找数据源出现错误!可能原因: " + e.getMessage());
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

猜你喜欢

转载自115893520.iteye.com/blog/550236