Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the full query that a PreparedStatement is about to execute? [duplicate]

I'm working with PreparedStatement with MySQL Server.

example:

String myQuery = "select id from user where name = ?";
PreparedStatement stmt  = sqlConnection.prepareStatement(myQuery);
stmt.setString(1, "test");
stmt.executeQUery();
ResultSet rs = stmt.getResultSet();

How can I receive the full SQL query that is about to be executed on the MySQL Server?

like image 756
ufk Avatar asked Jun 14 '10 15:06

ufk


People also ask

Can I use same PreparedStatement multiple times?

You can execute a given prepared statement multiple times, passing different variables to it or setting the variables to different values before each execution. For examples, see Section 13.5, “Prepared Statements”.

Can we use PreparedStatement for SELECT query?

To retrieve data from a table using a SELECT statement with parameter markers, you use the PreparedStatement.

Is PreparedStatement is less efficient than statement?

PreparedStatement provides different types of setter methods to set the input parameters for the query. PreparedStatement is faster than Statement. It becomes more visible when we reuse the PreparedStatement or use it's batch processing methods for executing multiple queries.

How much faster are prepared statements?

Prepared statements are much faster when you have to run the same statement multiple times, with different data. Thats because SQL will validate the query only once, whereas if you just use a statement it will validate the query each time.


1 Answers

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!
like image 193
gustafc Avatar answered Oct 29 '22 04:10

gustafc