13

When we create a PreparedStatement we use '?' chars to then be replaced by setted parameters.

How can we see the final SQL string after these parameters are set?

Hikari
  • 3,797
  • 12
  • 47
  • 77
  • See: [How can I get the SQL of a PreparedStatement?](http://stackoverflow.com/questions/2382532/how-can-i-get-the-sql-of-a-preparedstatement) – Reimeus Mar 21 '13 at 16:28

2 Answers2

11

There is no final SQL string, the version with placeholders is what is actually sent to server. The data is sent completely separately from it as you execute queries on the prepared statement.

You can log the string with placeholders, and then each dataset individually.

Your code could combine them in the log to an actual SQL string if that's what you want:

String query = "SELECT a FROM b WHERE c = ?";

...

pstmt.setString(1, "asd");
logSQL( query, "asd");

logSQL would then actually log "SELECT a FROM b WHERE c = 'asd'". Could be that someone has actually implemented this before...

Community
  • 1
  • 1
Esailija
  • 138,174
  • 23
  • 272
  • 326
5

The easiest way (that works with any JDBC driver) is to use log4jdbc. It's a proxy that wraps the driver, creates a readable SQL string by combining the SQL and its parameters and logs it, then passes the SQL and parameters on to the underlying driver.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276