Tomcat 链接池

Tomcat 链接池
 1 package  com.lucky.util;
 2
 3 import  java.sql.Connection;
 4 import  java.sql.SQLException;
 5
 6 import  javax.naming.Context;
 7 import  javax.naming.InitialContext;
 8 import  javax.naming.NamingException;
 9 import  javax.sql.DataSource;
10
11 public   class  BaseDb  {
12    private Connection conn = null;
13    private DataSource dataSource   = null;
14    public BaseDb(){
15        init();
16    }

17    private void init(){
18        try {
19            Context ctx = new InitialContext();
20            dataSource = (DataSource) ctx.lookup("java:/comp/env/jdbc/mysql");
21            conn = dataSource.getConnection();
22        }
 catch (NamingException e) {
23            // TODO Auto-generated catch block
24            e.printStackTrace();
25        }
 catch (SQLException e) {
26            // TODO Auto-generated catch block
27            e.printStackTrace();
28        }

29    }

30}

31
在tomcat server.xml
 1
 2 < Context path = " /test "  docBase = " F:\WorkSpace\workspace_shangluo\TomcatPool\WebRoot "  debug = " 0 " >  
 3            < Resource name = " jdbc/mysql "  auth = " Container "  type = " javax.sql.DataSource " />  
 4            < ResourceParams name = " jdbc/mysql " >  
 5              < parameter >  
 6                < name > factory </ name >  
 7                < value > org.apache.commons.dbcp.BasicDataSourceFactory </ value >  
 8              </ parameter >  
 9              < parameter >  
10                < name > driverClassName </ name >  
11                < value > com.mysql.jdbc.Driver </ value >  
12              </ parameter >  
13              < parameter >  
14                < name > url </ name >  
15                < value > jdbc:mysql: // localhost/lucky</value> 
16              </ parameter >  
17              < parameter >  
18                < name > username </ name >  
19                < value > root </ value >
20              </ parameter >  
21              < parameter >  
22                < name > password </ name >  
23                < value > 123456 </ value >  
24              </ parameter >  
25              < parameter >  
26                < name > maxActive </ name >  
27                < value > 20 </ value >  
28              </ parameter >  
29              < parameter >  
30                < name > maxIdle </ name >  
31                < value > 10 </ value >  
32              </ parameter >  
33              < parameter >  
34                < name > maxWait </ name >  
35                < value >- 1 </ value >  
36              </ parameter >  
37            </ ResourceParams >  
38 </ Context >
39
40

然后在web项目的web.xml中定义
1 < resource - ref >
2          < res - ref - name > jdbc / mysql </ res - ref - name >
3          < res - type > javax.sql.DataSource </ res - type >
4          < res - auth > Container </ res - auth >
5      </ resource - ref >

下来就可以在程序用调用了

你可能感兴趣的:(Tomcat 链接池)