我可以获取准备执行的完整查询吗?
问题描述:
我正在使用PreparedStatement和MySQL服务器.
I'm working with PreparedStatement with MySQL server.
示例:
String myQuery = "select id from user where name = ?";
PreparedStatement stmt = sqlConnection.prepareStatement(myQuery);
stmt.setString(1, "test");
stmt.executeQUery();
ResultSet rs = stmt.getResultSet();
如何接收将在MySQL服务器上执行的完整SQL查询?
How can I receive the full SQL query that is about to be executed on the MySQL server?
谢谢!
答
JDBC规范没有对此进行强制规定,但是一些JDBC驱动程序使PreparedStatement的toString返回将要运行的查询的排序,而MySQL的Connector/J恰好具有这种行为(或者至少是几年前).
It's not mandated by the JDBC spec, but several JDBC drivers let the toString of a PreparedStatement return sort-of the query that will be run, and MySQL's Connector/J happens to have this behavior (or at least it did a few years ago).
String myQuery = "select id from user where name = ?";
PreparedStatement stmt = sqlConnection.prepareStatement(myQuery);
stmt.setString(1, "test");
System.out.println(stmt); // May do what you want!