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?
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.
'statement compilation' is something that happens on the database which helps it return results faster and more efficiently. If you use a PreparedStatement then it allows the database to reuse a statement which was already compiled and saves having to do it again. Bad SQL will likely result in a badly compiles database statement, but not always.