How to establish a connection pool in JDBC?

前端 未结 13 2636
一个人的身影
一个人的身影 2020-11-22 02:43

Can anybody provide examples or links on how to establish a JDBC connection pool?

From searching google I see many different ways of doing this and it is rather conf

13条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 02:49

    If you need a standalone connection pool, my preference goes to C3P0 over DBCP (that I've mentioned in this previous answer), I just had too much problems with DBCP under heavy load. Using C3P0 is dead simple. From the documentation:

    ComboPooledDataSource cpds = new ComboPooledDataSource();
    cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver
    cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" );
    cpds.setUser("swaldman");
    cpds.setPassword("test-password");
    
    // the settings below are optional -- c3p0 can work with defaults
    cpds.setMinPoolSize(5);
    cpds.setAcquireIncrement(5);
    cpds.setMaxPoolSize(20);
    
    // The DataSource cpds is now a fully configured and usable pooled DataSource 
    

    But if you are running inside an application server, I would recommend to use the built-in connection pool it provides. In that case, you'll need to configure it (refer to the documentation of your application server) and to retrieve a DataSource via JNDI:

    DataSource ds = (DataSource) new InitialContext().lookup("jdbc/myDS");
    

提交回复
热议问题