如何使用Spring的JdbcTemplate重用相同的连接? [英] How to reuse the same connection with a Spring's JdbcTemplate?
本文介绍了如何使用Spring的JdbcTemplate重用相同的连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
@Test
public void springTest() throws SQLException{
//Connect to the DB.
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:/data/h2/testa");
dataSource.setUsername("");
dataSource.setPassword("");
JdbcTemplate jt=new JdbcTemplate(dataSource);
jt.execute("SELECT 1");
jt.execute("SELECT 1");
}
我希望两条execute()行重用相同的连接。但是,日志输出说:
I expect the two execute() lines to reuse the same connection. However, the log output says:
2011-02-10 12:24:17 DriverManagerDataSource [INFO] Loaded JDBC driver: org.h2.Driver
2011-02-10 12:24:17 JdbcTemplate [DEBUG] Executing SQL statement [SELECT 1]
2011-02-10 12:24:17 DataSourceUtils [DEBUG] Fetching JDBC Connection from DataSource
2011-02-10 12:24:17 DriverManagerDataSource [DEBUG] Creating new JDBC DriverManager Connection to [jdbc:h2:/data/h2/testa]
2011-02-10 12:24:17 DataSourceUtils [DEBUG] Returning JDBC Connection to DataSource
2011-02-10 12:24:17 JdbcTemplate [DEBUG] Executing SQL statement [SELECT 1]
2011-02-10 12:24:17 DataSourceUtils [DEBUG] Fetching JDBC Connection from DataSource
2011-02-10 12:24:17 DriverManagerDataSource [DEBUG] Creating new JDBC DriverManager Connection to [jdbc:h2:/data/h2/testa]
2011-02-10 12:24:17 DataSourceUtils [DEBUG] Returning JDBC Connection to DataSource
上面的例子运行得非常快,但我有一个更大的p代码基本上做同样的事情,并在创建新的JDBC DriverManager连接
上长时间挂起。我从来没有得到错误,但它使代码运行得非常慢。我可以以某种方式重构上面的代码只是使用相同的连接吗?
The above example runs quite fast but I have a larger piece of code that does basically the same thing and hangs for a long time on Creating new JDBC DriverManager Connection
. I never get an error but it makes the code run very slowly. Can I somehow refactor the above code to just use the same connection?
谢谢
推荐答案
以下是使用Apache DBCP的示例: -
Here's an example using Apache DBCP:-
BasicDataSource dbcp = new BasicDataSource();
dbcp.setDriverClassName("com.mysql.jdbc.Driver");
dbcp.setUrl("jdbc:mysql://localhost/test");
dbcp.setUsername("");
dbcp.setPassword("");
JdbcTemplate jt = new JdbcTemplate(dbcp);
jt.execute("SELECT 1");
jt.execute("SELECT 1");
log4j输出为: -
The log4j output is:-
[DEBUG] [JdbcTemplate] [execute:416] - Executing SQL statement [SELECT 1]
[DEBUG] [DataSourceUtils] [doGetConnection:110] - Fetching JDBC Connection from DataSource
[DEBUG] [DataSourceUtils] [doReleaseConnection:332] - Returning JDBC Connection to DataSource
[DEBUG] [JdbcTemplate] [execute:416] - Executing SQL statement [SELECT 1]
[DEBUG] [DataSourceUtils] [doGetConnection:110] - Fetching JDBC Connection from DataSource
[DEBUG] [DataSourceUtils] [doReleaseConnection:332] - Returning JDBC Connection to DataSource
这篇关于如何使用Spring的JdbcTemplate重用相同的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文