How to establish a connection pool in JDBC?

前端 未结 13 2294
一个人的身影
一个人的身影 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:56

    Don't reinvent the wheel.

    Try one of the readily available 3rd party components:

    • Apache DBCP - This one is used internally by Tomcat, and by yours truly.
    • c3p0

    Apache DBCP comes with different example on how to setup a pooling javax.sql.DataSource. Here is one sample that can help you get started.

    0 讨论(0)
  • 2020-11-22 03:01

    MiniConnectionPoolManager is a one-java-file implementation, if you're looking for an embeddable solution and are not too concerned about performances (though I haven't tested it in that regard).

    It is multi-licensed EPL, LGPL and MPL.

    Its documentation also gives alternatives worth checking (on top of DBCP and C3P0):

    • Proxool
    • BoneCP
    • Tomcat JDBC Connection Pool
    0 讨论(0)
  • 2020-11-22 03:07

    Apache Commons has a library for that purpose: DBCP. Unless you have strange requirements around your pools, I'd use a library as it's bound to be trickier and more subtle than you would hope.

    0 讨论(0)
  • 2020-11-22 03:09

    As answered by others, you will probably be happy with Apache Dbcp or c3p0. Both are popular, and work fine.

    Regarding your doubt

    Doesn't javax.sql or java.sql have pooled connection implementations? Why wouldn't it be best to use these?

    They don't provide implementations, rather interfaces and some support classes, only revelant to the programmers that implement third party libraries (pools or drivers). Normally you don't even look at that. Your code should deal with the connections from your pool just as they were "plain" connections, in a transparent way.

    0 讨论(0)
  • 2020-11-22 03:11

    I would recommend using the commons-dbcp library. There are numerous examples listed on how to use it, here is the link to the move simple one. The usage is very simple:

     BasicDataSource ds = new BasicDataSource();
     ds.setDriverClassName("oracle.jdbc.driver.OracleDriver")
     ds.setUsername("scott");
     ds.setPassword("tiger");
     ds.setUrl(connectURI);
     ...
     Connection conn = ds.getConnection();
    

    You only need to create the data source once, so make sure you read the documentation if you do not know how to do that. If you are not aware of how to properly write JDBC statements so you do not leak resources, you also might want to read this Wikipedia page.

    0 讨论(0)
  • 2020-11-22 03:11

    Vibur DBCP is another library for that purpose. Several examples showing how to configure it for use with Hibernate, Spring+Hibernate, or programatically, can be found on its website: http://www.vibur.org/

    Also, see the disclaimer here.

    0 讨论(0)
提交回复
热议问题