I am using MySQL
in Java
. I don\'t have a good understanding of PreparedStatement
.
I know it is better to use PreparedStatem
It is already translated into code the database server understands. Only placeholders are left for the variables you are inserting.
For example a Java program also has to be compiled from source code to byte-code, where the soruce code is the human readable for of the program and the bytecode is the representation if the source code which is also understood by the machine
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.
You generally use prepared statement with bind variables where you provide the variables at run time. Now what happens for successive execution of prepared statements, you can provide the variables which are different from previous calls. From DB point of view, it does not have to compile the statement every time, will just insert the bind variables at rum time. So becomes faster.
Other advantages of prepared statements are :-
1)protection against SQL-injection attack
2) Faster for successive calls of same statements
How it works :-
Precompilation is done by the database. Some simpler databases don't precompile statements at all. Others might precompile it on the prepareStatement call, and yet others might do it when execute is first called on the statement, taking values of the parameters into account when compiling (creating a plan for) the statement.
Databases that do precompile statements usually cache them, so in all probability ps1 won't be compiled again. Some JDBC drivers (eg. Oracle's) even cache prepared statements, so they haven't actually closed it when ps.close() was called.
Databases generally cache statements until something evicts them from the cache.
For details go through this wiki link
At a high level, there are two steps in running a SQL query. First, the query is compiled from a text format to an internal representation of the processing that needs to be done. The second is that that processing is then done.
What "pre-compiled" means is that the first step has been completed, so it doesn't need to be done again. The compilation phase can require some effort, particularly to find the best optimizations for the execution path (what indexes to use, what join methods, and so on). For simple queries, this can add overhead. For more complex queries, the overhead is usually much less than the effort to actually run the queries.
As an example of how this can have an effect. Consider a table with no indexes. You can create a compiled query that will do a full table scan. If you later add an index, the compiled query cannot use the index because it didn't know about it at compile time.
In the MySQL documentation, the compilation phase is mostly described as the optimization phase.