如何在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()行可以重用同一连接。但是,日志输出显示:
2011-02-10 12:24:17 DriverManagerDataSource [INFO]加载的JDBC驱动程序:org.h2.Driver2011-02-10 12:24:17 JdbcTemplate [DEBUG]执行SQL语句[SELECT 1]
2011-02-10 12:24:17 DataSourceUtils [DEBUG]从DataSource获取JDBC连接
2011-02-10 12:24:17 DriverManagerDataSource [DEBUG]创建与[jdbc:h2:/ data / h2 / testa]的新JDBC DriverManager连接
2011-02-10 12:24:17 DataSourceUtils [DEBUG]将JDBC连接返回到DataSource
2011-02-10 12:24:17 JdbcTemplate [DEBUG]执行SQL语句[SELECT 1]
2011-02-10 12:24:17 DataSourceUtils [DEBUG]从DataSource获取JDBC连接
2011-02-10 12:24:17 DriverManagerDataSource [DEBUG]创建与[jdbc:h2:/ data / h2 / testa]的新JDBC DriverManager连接
2011-02-10 12:24:17 DataSourceUtils [DEBUG]将JDBC连接返回到DataSource
上面的例子运行得很快,但是我有一段更大的代码,基本上做同样的事情,并且挂了很久Creating new JDBC DriverManager
Connection。我从来没有收到错误,但是它使代码运行非常缓慢。我可以以某种方式重构以上代码以仅使用相同的连接吗?
谢谢
回答:
这是使用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输出为:-
[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中重用相同的连接? 的全部内容, 来源链接: utcz.com/qa/413187.html