如何获取 PreparedStatement 的 SQL? [英] How can I get the SQL of a PreparedStatement?

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

问题描述

我有一个具有以下方法签名的通用 Java 方法:

I have a general Java method with the following method signature:

private static ResultSet runSQLResultSet(String sql, Object... queryParams)

它打开一个连接,使用sql语句和queryParams可变长度数组中的参数构建一个PreparedStatement,运行它,缓存ResultSet(在 CachedRowSetImpl 中),关闭连接,并返回缓存的结果集.

It opens a connection, builds a PreparedStatement using the sql statement and the parameters in the queryParams variable length array, runs it, caches the ResultSet (in a CachedRowSetImpl), closes the connection, and returns the cached result set.

我在记录错误的方法中有异常处理.我将 sql 语句记录为日志的一部分,因为它对调试非常有帮助.我的问题是记录字符串变量 sql 会用 ? 而不是实际值记录模板语句.我想记录已执行(或尝试执行)的实际语句.

I have exception handling in the method that logs errors. I log the sql statement as part of the log since it's very helpful for debugging. My problem is that logging the String variable sql logs the template statement with ?'s instead of actual values. I want to log the actual statement that was executed (or tried to execute).

所以...有没有办法获得将由 PreparedStatement 运行的实际 SQL 语句?(没有自己构建它.如果我找不到访问PreparedStatement的 SQL的方法,我可能最终会在我的catch<中自己构建它/code>es.)

So... Is there any way to get the actual SQL statement that will be run by a PreparedStatement? (Without building it myself. If I can't find a way to access the PreparedStatement's SQL, I'll probably end up building it myself in my catches.)

推荐答案

使用预处理语句,没有SQL查询":

Using prepared statements, there is no "SQL query" :

  • 您有一个包含占位符的语句
    • 它被发送到数据库服务器
    • 并在那里准备
    • 这意味着 SQL 语句被分析"、解析,一些表示它的数据结构是在内存中准备的
    • 发送到服务器
    • 并执行准备好的语句——处理这些数据

    但是没有重新构建实际的 SQL 查询——无论是在 Java 端,还是在数据库端.

    But there is no re-construction of an actual real SQL query -- neither on the Java side, nor on the database side.

    因此,无法获得准备好的语句的 SQL —— 因为没有这样的 SQL.

    So, there is no way to get the prepared statement's SQL -- as there is no such SQL.


    出于调试目的,解决方案是:


    For debugging purpose, the solutions are either to :

    • 输出语句的代码,包含占位符和数据列表
    • 或者手动"构建"一些 SQL 查询.

    这篇关于如何获取 PreparedStatement 的 SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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