java 如何查看 PreparedStatement 的 SQL 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15552980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to see PreparedStatement's SQL string?
提问by Hikari
When we create a PreparedStatement we use '?' chars to then be replaced by setted parameters.
当我们创建一个 PreparedStatement 时,我们使用 '?' 然后用设置的参数替换字符。
How can we see the final SQL string after these parameters are set?
设置完这些参数后如何才能看到最终的SQL字符串呢?
采纳答案by Nathan Hughes
The easiest way (that works with any JDBC driver) is to use log4jdbc. It's a proxy that wraps the driver, creates a readable SQL string by combining the SQL and its parameters and logs it, then passes the SQL and parameters on to the underlying driver.
最简单的方法(适用于任何 JDBC 驱动程序)是使用log4jdbc。它是一个包装驱动程序的代理,通过组合 SQL 及其参数创建可读的 SQL 字符串并记录它,然后将 SQL 和参数传递给底层驱动程序。
回答by Esailija
There is no final SQL string, the version with placeholders is what is actually sent to server. The data is sent completely separately from it as you execute queries on the prepared statement.
没有最终的 SQL 字符串,带有占位符的版本是实际发送到服务器的内容。当您在准备好的语句上执行查询时,数据与它完全分开发送。
You can log the string with placeholders, and then each dataset individually.
您可以使用占位符记录字符串,然后单独记录每个数据集。
Your code could combine them in the log to an actual SQL string if that's what you want:
如果这是您想要的,您的代码可以将它们在日志中组合成一个实际的 SQL 字符串:
String query = "SELECT a FROM b WHERE c = ?";
...
pstmt.setString(1, "asd");
logSQL( query, "asd");
logSQL
would then actually log "SELECT a FROM b WHERE c = 'asd'"
. Could be that someone has actually implemented this before...
logSQL
然后实际上会记录"SELECT a FROM b WHERE c = 'asd'"
. 可能是有人之前实际实施过这个......