0

how to create JDBC connection pool with configurable parameters, client should able to change the default number of connection ??? can anybody explain this with sample code

2 Answers2

1

I hope this will help you.

  import java.sql.Connection;
  import java.sql.ResultSet;
  import java.sql.Statement;
  import org.apache.tomcat.jdbc.pool.DataSource;
  import org.apache.tomcat.jdbc.pool.PoolProperties;


  public class SimplePOJOExample {

  public static void main(String[] args) throws Exception {
      PoolProperties p = new PoolProperties();
      p.setUrl("jdbc:mysql://localhost:3306/mysql");
      p.setDriverClassName("com.mysql.jdbc.Driver");
      p.setUsername("root");
      p.setPassword("password");
      p.setJmxEnabled(true);
      p.setTestWhileIdle(false);
      p.setTestOnBorrow(true);
      p.setValidationQuery("SELECT 1");
      p.setTestOnReturn(false);
      p.setValidationInterval(30000);
      p.setTimeBetweenEvictionRunsMillis(30000);
      p.setMaxActive(100);
      p.setInitialSize(10);
      p.setMaxWait(10000);
      p.setRemoveAbandonedTimeout(60);
      p.setMinEvictableIdleTimeMillis(30000);
      p.setMinIdle(10);
      p.setLogAbandoned(true);
      p.setRemoveAbandoned(true);
      p.setJdbcInterceptors(
        "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
        "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
      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) {}
      }
  }

 }

Source : https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html

Dilip Belgumpi
  • 668
  • 4
  • 13
0

You can use OracleDataSource as well, supported with Ojdbc6.jar. The concept remains same but will differ based on what libraries you choose.

Also, As a general practice, you should put all the setter parameters in a properties file.

PankajT
  • 145
  • 3