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

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

问题描述

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

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

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

它打开一个连接,构建一个 PreparedStatement 使用sql语句和 queryParams 变量长度数组中的参数,运行它,缓存 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语句记录为日志的一部分,因为它对调试很有帮助。我的问题是记录String变量 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 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天全站免登陆