JDBC Connection pooling using C3P0

浪尽此生 提交于 2019-11-29 22:17:05

With a pooled data source, the connections in the pool are not actually closed, they just get returned to the pool. However, when the application is shut down, those connections to the database should be properly and actually closed, which is where the final cleanup comes in.

Incidentally, the c3p0 project is pretty much dead in the water, I recommend you use Apache Commons DBCP instead, it's still being maintained.

DAOs should not be responsible for acquiring a connection to the database. They have no way to know when they're being used as part of a larger transaction. You should be passing the data source or connection instance into the DAO.

If any of the calls to close in your finally block throw an exception, none of the ones that follow will be called. Each one needs to be in its own try/catch block. I put them into a utility class as static methods.

The code looks fine to me, but I would write a helper method that does the close operations or you'll get this verbose finally-block in every DAO or method. Maybe you should write three separate try-catch-blocks around the close Operations, to make sure the connection is closed no matter if the statement and resultset have thrown an exection. Also note that the javadoc says

When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

So you don't need to close the resultset in the above example, but you could.

The linked cleanup method is for closing the datasource, what isn't needed in most projects because the DS lives as long as your app is running.

I use Play Framework and Scala, so the following example is in play project.

Step1. configuration

In build.sbt, if you use mysql/hive as database, you need to add these properties.

libraryDependencies ++ = Seq (
   jdbc,
  "mysql" % "mysql-connector-java" % "5.1.31",
  "org.apache.hive" % "hive-jdbc" % "0.12.0",
  "com.mchange" % "c3p0" % "0.9.2.1"
)

Step2. how to access it? you need to import c3p0 library.

import com.mchange.v2.c3p0.ComboPooledDataSource

Step3. and then you need to create instance.

val cpds = new ComboPooledDataSource()
cpds.setDriverClass(...)
cpds.setJdbcUrl(...)
cpds.setUser(...)
cpds.setPassword(...)

Step4. you get a connection

cpds.getConnection
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!