Get query from java.sql.PreparedStatement

llm picture llm · Apr 21, 2010 · Viewed 314.4k times · Source

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

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

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.

Answer

BalusC picture BalusC · Apr 21, 2010

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

To my experience, the ones which do so are at least the PostgreSQL 8.x and MySQL 5.x JDBC drivers. For the case your JDBC driver doesn't support it, your best bet is using a statement wrapper which logs all setXxx() methods and finally populates a SQL string on toString() based on the logged information. For example Log4jdbc or P6Spy.