如何从Oracle JDBC PreparedStatement对象获取绑定参数的值 [英] How to get values of bind parameters from Oracle JDBC PreparedStatement object

查看:206
本文介绍了如何从Oracle JDBC PreparedStatement对象获取绑定参数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在使用Oracle JDBC时使用实际绑定参数实现所有已执行语句的日志记录。我希望我可以创建这样的日志记录方法,只将PreparedStatement对象作为参数传递。

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.

例如我创建了PreparedStatement并绑定了一个参数

For example I have created PreparedStatement and have bound one parameter

PreparedStatement ps = conn.prepareStatement(
    "SELECT * FROM employees WHERE employee_id = ?");
ps.setInt(1,1);

现在我希望能够从ps获得实际的SQL语句SELECT * FROM employees WHERE employe_id = 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.

到目前为止,我发现我可以使用

So far I found that I can use

((oracle.jdbc.driver.OracleStatement) ps).getOriginalSql()

获取

SELECT * FROM employees WHERE employe_id = ?

现在我需要一些方法从ps获取当前绑定变量的列表,以便我可以替换?使用绑定参数值。

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.getClass()。getDeclaredFields()和ps.getClass()。getSuperclass()。getDeclaredFields()但是远远找不到存储绑定参数值及其类型的位置。

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.

有什么建议在哪里寻找它们?

Any suggestions where to look for them?

推荐答案

大多数日志记录框架都有嵌套诊断上下文。当你填写准备好的陈述时,你可以在那里保存你的查询及其参数。

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;
}

这篇关于如何从Oracle JDBC PreparedStatement对象获取绑定参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆