简体   繁体   中英

Use DriverManager with Tomcat connection pooling

Here is a code snippet using Tomcat's builtin pooling mechanism.

PoolProperties p = new PoolProperties();
p.setUrl("jdbc:mysql://localhost:3306/mysql");
p.setDriverClassName("com.mysql.jdbc.Driver");
p.setUsername("root");
p.setPassword("password");
DataSource datasource = new DataSource();
datasource.setPoolProperties(p);
Connection con = null;
try {
   con = datasource.getConnection();
   Statement st = con.createStatement();
   ResultSet rs = st.executeQuery("select * from user");
   int cnt = 1;
   while (rs.next()) {
       System.out.println((cnt++)+". Host:" +rs.getString("Host")+
       " User:"+rs.getString("User")+" Password:"+rs.getString("Password"));
   }
   rs.close();
   st.close();
} finally {
   if (con!=null) try {con.close();}catch (Exception ignore) {}
}

How would I do this without using DataSource but a DriverManager?

It seems it's not possible to do the same with DriverManager. In fact, it's why they came up with the improved DataSource class in JDBC 2.0.

To use connection pooling with DriverManager, we have 3 options

  1. Write your own implementation. More details here .
  2. Use a framework/library like apache-commons-dbcp. More details here .
  3. Use the container provided DataSource. Sample here (based on tomcat container).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM