从 java.sql.PreparedStatement 获取查询 [英] Get query from java.sql.PreparedStatement

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

问题描述

在我的代码中,我使用了 java.sql.PreparedStatement.

In my code I am using java.sql.PreparedStatement.

然后我执行 setString() 方法来填充准备好的语句的通配符.

I then execute the setString() method to populate the wildcards of the prepared statement.

在调用 executeQuery() 方法并执行查询之前,有没有办法让我检索(并打印出)最终查询?我只是想要这个用于调试目的.

Is there a way for me to retrieve (and print out) the final query before the executeQuery() method is called and the query is executed? I Just want this for debugging purposes.

推荐答案

这在 JDBC API 契约中没有定义,但如果你幸运,有问题的 JDBC 驱动程序可能会返回完整的SQL 只需调用 PreparedStatement#toString().即

This is nowhere definied in the JDBC API contract, but if you're lucky, the JDBC driver in question may return the complete SQL by just calling PreparedStatement#toString(). I.e.

System.out.println(preparedStatement);

根据我的经验,目前至少有 PostgreSQL 8.x 和 MySQL 5.x JDBC 驱动程序.

To my experience, the ones which currently do so are at least the PostgreSQL 8.x and MySQL 5.x JDBC drivers.

如果您的 JDBC 驱动程序不支持它,最好的办法是使用语句包装器,它记录对 setXxx() 方法的所有调用,并最终在 上填充 SQL 字符串toString() 基于记录的信息.一个现有的库是 P6Spy.同时,向您的 JDBC 驱动程序的开发团队发布增强请求,并希望他们也能实现所需的 toString() 行为.

In the case that your JDBC driver doesn't support it, your best bet is using a statement wrapper which records all calls to setXxx() methods and finally populates a SQL string on toString() based on the recorded information. An existing library which does that is P6Spy. In the meanwhile, post an enhancement request to the development team of your JDBC driver and hope that they'll implement the desired toString() behavior as well.

这篇关于从 java.sql.PreparedStatement 获取查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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