tomcat配置数据池

1->配置servlet.xml

在 <GlobalNamingResources></GlobalNamingResources>中添加<Resource>

<Resource name="jdbc/DBPool" 
     type="javax.sql.DataSource"
    maxActive="100" 
    maxIdle="30" 
    maxWait="10000" 
    username="root" 
    password="root" 
    driverClassName="com.mysql.jdbc.Driver" 
    url= "jdbc:mysql://localhost:3306/friend"/>

 

2->配置web.xml

在<web-app>标签在添加<resource-ref>

<resource-ref>
    <res-ref-name>jdbc/DBPool</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

 

 

 

3->测试代码

Connection con;
       public    Connection getPoolConnection(){
  try {
            
            Context env = (Context)new InitialContext().lookup("java:comp/env");
            DataSource pool = (DataSource)env.lookup("jdbc/DBPool");
            if(pool==null)  System.out.println("null");
            con = pool.getConnection();
            System.out.println("succed");
        } catch (Exception ee) {
            System.out.println(ee.getMessage());
            return null;
        }
        return con;
    }

 

 

ps:要导入相应的数据库驱动

你可能感兴趣的:(tomcat)