0

Is there a way we can print prepared statement as a string with all the placeholders replaces with its actual values

  1. I'm using Oracle 11g and Java 1.6
  2. Using log4j packages for logging
Lohith
  • 57
  • 1
  • 2
  • 10
  • There are probably many, how are you executing your sql queries? (Hibernate? plain JDBC?) –  May 12 '17 at 14:57
  • I'm using a plain JDBC – Lohith May 12 '17 at 14:59
  • What we really need is a method that will let us obtain the query string with parameter placeholders replaced with actual values. Because java.sql.PreparedStatement has no such method we have to implement one ourselves. – Lohith May 15 '17 at 08:01

4 Answers4

1

you can use log4j.properties

log4j.logger.java.sql.PreparedStatement=DEBUG

Maybe you can describe better what you have in your project for get better answers

Guilherme
  • 593
  • 1
  • 6
  • 23
0

If you're executing the query and expect that you'll have a definite ResultSet then the following call ResultSet's getStatement() method will definitely help.

ResultSet resultSet = preparedStatement.executeQuery();
String executedQuery = resultSet.getStatement().toString();

You either use System.out.println(executedQuery) or log4J as you state, that's your choice of implementation.

Hope this helps!

N00b Pr0grammer
  • 4,503
  • 5
  • 32
  • 46
  • I got the below output: INFO: [UCaaSReportsUtil] : getServiceReportData: executedQuery oracle.jdbc.driver.OraclePreparedStatementWrapper@98644313 This is nothing but preparedSTatement.toString() – Lohith May 12 '17 at 15:39
0

As you are using Oracle's JDBC driver, you will get OraclePreparedStatement object when you call connection.preparedStatement(sql). Here's the javadoc for it and as it does not override toString() method, you will see a hash of the object on calling toString() (default implementation).

In this case, the only option is to write your own method that accepts String sql and parameters and prints pretty String.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

As you are using plain jdbc with Oracle driver, I will try a configuration similar to the one described in this oracle post:

https://docs.oracle.com/cd/B28359_01/java.111/b31224/diagnose.htm

Another thing you can do is install JProfiler, there is a Database configuration there that you can use to trace every call that your application is doing to your database.

You also can set the log4j property that was described in another response. If you do it this way, remember to set the log4j root logger into TRACE/DEBUG mode.

Fabri Pautasso
  • 485
  • 6
  • 17