I have a general Java method with the following method signature:
private static ResultSet runSQLResultSet(String sql, Object... queryParams)
It opens a connection, builds a PreparedStatement
using the sql statement and the parameters in the queryParams
variable length array, runs it, caches the ResultSet
(in a CachedRowSetImpl
), closes the connection, and returns the cached result set.
I have exception handling in the method that logs errors. I log the sql statement as part of the log since it's very helpful for debugging. My problem is that logging the String variable sql
logs the template statement with ?'s instead of actual values. I want to log the actual statement that was executed (or tried to execute).
So... Is there any way to get the actual SQL statement that will be run by a PreparedStatement
? (Without building it myself. If I can't find a way to access the PreparedStatement's
SQL, I'll probably end up building it myself in my catch
es.)
I'm using Java 8, JDBC driver with MySQL connector v. 5.1.31.
I may get real SQL string using this method:
So it returns smth like this:
Code Snippet to convert SQL PreparedStaments with the list of arguments. It works for me
If you're executing the query and expecting a
ResultSet
(you are in this scenario, at least) then you can simply callResultSet
'sgetStatement()
like so:The variable
executedQuery
will contain the statement that was used to create theResultSet
.Now, I realize this question is quite old, but I hope this helps someone..
I implemented the following code for printing SQL from PrepareStatement
If you're using MySQL you can log the queries using MySQL's query log. I don't know if other vendors provide this feature, but chances are they do.
To do this you need a JDBC Connection and/or driver that supports logging the sql at a low level.
Take a look at log4jdbc