如何从 Oracle JDBC PreparedStatement 对象获取绑定参数的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1130886/
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 get values of bind parameters from Oracle JDBC PreparedStatement object
提问by Raimonds Simanovskis
I want to implement logging of all executed statements with actual bind parameters when using Oracle JDBC. And I would prefer that I could create such logging method only passing PreparedStatement object as parameter.
我想在使用 Oracle JDBC 时使用实际绑定参数实现所有已执行语句的日志记录。我更希望我可以创建这样的日志记录方法,只将 PreparedStatement 对象作为参数传递。
For example I have created PreparedStatement and have bound one parameter
例如,我创建了 PreparedStatement 并绑定了一个参数
PreparedStatement ps = conn.prepareStatement(
"SELECT * FROM employees WHERE employee_id = ?");
ps.setInt(1,1);
Now I would like to be able to get from ps the actual SQL statement "SELECT * FROM employees WHERE employe_id = 1" that I could put in log file.
现在我希望能够从 ps 中获取我可以放入日志文件的实际 SQL 语句“SELECT * FROM Employees WHERE employee_id = 1”。
So far I found that I can use
到目前为止,我发现我可以使用
((oracle.jdbc.driver.OracleStatement) ps).getOriginalSql()
to get
要得到
SELECT * FROM employees WHERE employe_id = ?
Now I need some way to get the list of current bind variables from ps so that I could replace ? with bind parameter values.
现在我需要某种方法从 ps 获取当前绑定变量的列表,以便我可以替换 ? 与绑定参数值。
I tried to look in ps.getClass().getDeclaredFields() and ps.getClass().getSuperclass().getDeclaredFields() but so far couldn't find the place where bind parameter values and their types are stored.
我试图查看 ps.getClass().getDeclaredFields() 和 ps.getClass().getSuperclass().getDeclaredFields() 但到目前为止找不到存储绑定参数值及其类型的位置。
Any suggestions where to look for them?
任何建议在哪里寻找它们?
回答by akarnokd
Most logging framework have the notion for Nested Diagnostic Context. You could save your query and its parameters there when you fill up the prepared statement.
大多数日志框架都有嵌套诊断上下文的概念。当您填写准备好的语句时,您可以在那里保存您的查询及其参数。
Or, perhaps, do it in one step:
或者,也许,一步完成:
PreparedStatement fillAndLog(Connection conn, String query, Object... args) {
int i = 0;
PreparedStatement pstmt = conn.prepareStatement(query);
for (Object o : args) {
if (o instanceof String) {
pstmt.setString(i, (String)o);
} // else...
i++;
}
log.debug(String.format(query.replaceAll("\?", "%s"), args));
return pstmt;
}