Instantiating a JdbcTemplate from a java.sql.Connection

user321068 picture user321068 · Jun 24, 2010 · Viewed 12.2k times · Source

I want to obtain a JdbcTemplate in my Java code. I've already got a working java.sql.Connection. To create a new JdbcTemplate it would normally need an instance of the javax.sql.DataSource interface.

Is it somehow possible to obtain a new JdbcTemplatefrom an existing java.sql.Connection?

Answer

Bozho picture Bozho · Jun 24, 2010

Technically, you can, using SingleConnectionDataSource

new JdbcTemplate(new SingleConnectionDataSource(connection, false))

However, this is not quite advisable, unless for unit-tests for example.

You'd better use a full-featured DataSource and wire things using spring.