我正在使用 Spring 的 JdbcTemplate
(Spring 版本 4.1.4)。和我的类(class)'JdbcTemplate例如,我正在将选择查询作为准备好的语句进行。但是,我的查询意外地没有返回任何结果。因此,我确实需要调试我的查询并确保查询符合我的预期。
如何取回作为 JdbcTemplate
内部 PreparedStatement
一部分对数据库执行的实际 SQL?
我熟悉使用 PreparedStatement's toString() method来实现这一点,但由于 JDBCTemplate
在内部使用 PreparedStatement
,我不确定使用 Spring 的可行性。
我正在使用的一些示例代码如下:
private static final String PREPARED_QUERY =
"select\n" +
" spm.amount\n" +
"from\n" +
" search_price_modifier spm\n" +
"where\n" +
" spm.search_id = ?\n" +
" and spm.search_date > to_date(?, 'MM-DD-YYYY HH24:MI:SS')\n" +
" and spm.search_date < to_date(?, 'MM-DD-YYYY HH24:MI:SS')\n";
public void runQuery(String searchId, String strSearchDateInfimum,
String strSearchDateSupremum) {
SqlRowSet amounts = this.jdbcTemplate.queryForRowSet(
PREPARED_QUERY_FOR_FLAT_MARKUP_VERIFICATION,
searchId, strSearchDateInfimum, strSearchDateSupremum);
while (amounts.next()) {
float amount = amounts.getFloat("AMOUNT");
LOGGER.debug("amount=" + amount);
}
}
最佳答案
我将提供一种通用方法来调试所有语句,并在您需要时在控制台中查看它们,因为 spring 默认情况下会这样做 添加到您的类路径
All SQL issued by this class is logged at the DEBUG level under the category corresponding to the fully qualified class name of the template instance (typically JdbcTemplate, but it may be different if you are using a custom subclass of the JdbcTemplate class).
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration >
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console" />
</Root>
<Logger level="debug" name="org.springframework.jdbc">
<AppenderRef ref="Console" />
</Logger>
</Loggers>
</configuration>
添加到您的lib log4j-api-2.5.jar
log4j-core-2.5.jar
log4j-jcl.2.5.jar
和您现在可以开始了。
关闭调试 更改级别
<Logger level="error" name="org.springframework.jdbc">
<AppenderRef ref="Console" />
</Logger>
现在 spring 不会调试,但它只会打印错误
关于java - 使用 Spring 的 JDBCTemplate 时如何获取PreparedStatement 查询字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35562497/