Get query from java.sql.PreparedStatement [duplicate]

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 currently do so are at least the PostgreSQL 8.x and MySQL 5.x JDBC drivers.

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.

Leave a Comment