如何获取Oracle数据库的当前Connection对象?我在Spring 3.0.5中使用JDBC模块。
答案 0 :(得分:25)
从Connection
bean获取DataSource
。
您可以通过使用Spring依赖注入将其注入到bean中,或者通过静态访问ApplicationContext
来访问dataSource:
DataSource ds = (DataSource)ApplicationContextProvider.getApplicationContext().getBean("dataSource");
Connection c = ds.getConnection();
答案 1 :(得分:17)
使用DataSourceUtils.getConnection()
。
它返回与当前事务关联的连接(如果有)。
答案 2 :(得分:13)
只是一个信息: 我正在使用Spring JDBC Template,它为我保存当前的连接对象,可以按如下方式接收。
Connection con;
con = getJdbcTemplate().getDataSource().getConnection();
答案 3 :(得分:0)
我不确定最初发布此问题时是否可以使用此方法,但是,似乎在最新版本的Spring中,首选的方法是使用JdbcTemplate
和PreparedStatementCreator
。请参阅https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html#query-org.springframework.jdbc.core.PreparedStatementCreator-org.springframework.jdbc.core.PreparedStatementSetter-org.springframework.jdbc.core.ResultSetExtractor-或将query
作为第一个参数的其他任何PreparedStatementCreator
方法:
jdbcTemplate.query(con -> {
// add required logic here
return con.prepareStatement("sql");
}, rs -> {
//process row
});
与其他提供的答案(DataSourceUtils.getConnection()
或jdbcTemplate.getDataSource().getConnection()
相比,它具有优势,因为未未分配新连接,它使用与调用任何其他连接相同的连接管理jdbcTemplate
其他查询方法中的一种。因此,您也不必担心关闭/释放连接,因为spring会处理它。