Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does pre-compiling a JDBC PreparedStatement do?

What does "precompiling" a statement do, because I have seen that if I write a prepared statement with a bad SQL syntax that compilation does not report any problem!

So if precompiling a prepared statement doesn't check for syntax validity what really does it do?

like image 325
xdevel2000 Avatar asked Mar 31 '11 08:03

xdevel2000


People also ask

What is pre-compiled in PreparedStatement?

When you use prepared statement(i.e pre-compiled statement), As soon as DB gets this statement, it compiles it and caches it so that it can use the last compiled statement for successive call of same statement. So it becomes pre-compiled for successive calls.

What is the use of PreparedStatement in JDBC?

The PreparedStatement interface extends the Statement interface it represents a precompiled SQL statement which can be executed multiple times. This accepts parameterized SQL quires and you can pass 0 or more parameters to this query.

Why do we use PreparedStatement?

1. PreparedStatement allows you to write a dynamic and parametric query. By using PreparedStatement in Java you can write parameterized SQL queries and send different parameters by using the same SQL queries which is a lot better than creating different queries.


1 Answers

Creating a PreparedStatements may or may not involve SQL syntax validation or even DB server roundtrips, that depends entirely on the JDBC driver used. Some drivers will do a roundtrip or validate, others will not.

So on some JDBC drivers a PreparedStatement is no more "prepared" than a normal Statement. (In other words: with some JDBC drivers a PreparedStatement represents a server-side resource (similar to Connection), while on others it's a pure client-side construct).

An important difference, however is that a PreparedStatement will help you handle dynamic parameter values in a way that is guaranteed to avoid any escaping or formatting issues that you would have if you try to insert the values into the SQL statement string manually and execute it using a normal Statement.

That feature is indepdendent from the choice of "preparing" the statement beforehand or not, so it's provided by every JDBC driver, even if it doesn't do any other preparation steps.

like image 177
Joachim Sauer Avatar answered Sep 22 '22 19:09

Joachim Sauer