How can I get the SQL of a PreparedStatement?
Using prepared statements, there is no "SQL query" :
- You have a statement, containing placeholders
- it is sent to the DB server
- and prepared there
- which means the SQL statement is "analysed", parsed, some data-structure representing it is prepared in memory
- And, then, you have bound variables
- which are sent to the server
- and the prepared statement is executed -- working on those data
But there is no re-construction of an actual real SQL query -- neither on the Java side, nor on the database side.
So, there is no way to get the prepared statement's SQL -- as there is no such SQL.
For debugging purpose, the solutions are either to :
- Ouput the code of the statement, with the placeholders and the list of data
- Or to "build" some SQL query "by hand".
Get query from java.sql.PreparedStatement
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.
How to see PreparedStatement's SQL string?
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.
Can I get the full query that a PreparedStatement is about to execute?
It's not mandated by the JDBC spec, but several JDBC drivers let the toString
of a PreparedStatement
return sort-of the query that will be run, and MySQL's Connector/J happens to have this behavior (or at least it did a few years ago).
String myQuery = "select id from user where name = ?";
PreparedStatement stmt = sqlConnection.prepareStatement(myQuery);
stmt.setString(1, "test");
System.out.println(stmt); // May do what you want!
Is there a way we can print prepared statement as a string with all the placeholders replaces with its actual values
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
.
How to get SQL prepared statement based on user input (scanner)
Please refer to JDBC PreparedStatement example – Select list of the records
public static List<Reservation> checkDatesForReservation(Reservation reservation){
Reservation reservation = null;
List<Reservation> reservationList = new ArrayList<>();
String sql2= "SELECT ReservationStartDate, ReservationEndDate FROM treservations WHERE ReservationStartDate=? AND ReservationEndDate= ?";
try{
PreparedStatement ps = ConnectorDB.connection.prepareStatement(sql2);
ps.setString(1,reservation.getReservationStartDate());
ps.setString(2,reservation.getReservationEndDate());
ResultSet resultSet = ps.executeQuery();
while (resultSet.next()){
reservation = new Reservation();
reservation.setReservationStartDate(rs.getString("ReservationStartDate"));
reservation.setReservationEndDate(rs.getString("ReservationEndDate"));
reservationList.add(reservation);
}
}catch (SQLException e){
e.getStackTrace();
}
return reservationList;
}
How to get the full query that a PreparedStatement is about to execute in DB2?
If you are familiar with Debugging options in Eclipse. You may try the following:
Set a Breakpoint at
ResultSet resultSet = statement.executeQuery();
Right click your application, say
Debug As
selectJava Application
(or Whatever applicable in your case i.e. may be SpringBoot App etc.Perform step that gets you to code mentioned in the Question.
If you check
Variables tab
inDebug Perspective
of Eclipse, you will find variables likemyQuery
,stmt
(according to your code)Whatever you see as value of
stmt
would be the full SQL query you need.
Also, if you don't want to keep looking at this variable always you may try Java Logging
and Print your Full SQL query in Logs.
Related Topics
Is Method Reference Caching a Good Idea in Java 8
Java Time-Based Map/Cache with Expiring Keys
How to Parse Date String to Date
Why Is It Not Possible to Extend Annotations in Java
How to Use an Internet Time Server to Get the Time
Main Thread VS. UI Thread in Java
Convert Float to Double Without Losing Precision
Java: Error: Variable Might Not Have Been Initialized
Copy a Stream to Avoid "Stream Has Already Been Operated Upon or Closed"
Encrypt Password in Configuration Files
Convenient Way to Parse Incoming Multipart/Form-Data Parameters in a Servlet
How to Compare Two Dates Without the Time Portion
Effective Gif/Image Color Quantization
Convert Java.Util.Date to What "Java.Time" Type
Get Width and Height of JPAnel Outside of the Class
What Is an Object's Hash Code If Hashcode() Is Not Overridden