The main benefit of PreparedStatement
s is when you have code that behaves in a similar way to this pseudocode:
PreparedStatement ps = con.prepareStatement("blabalblabla");
for (int i = 0; i < a gazillion times; i++) {
// Set parameters into ps
...
// execute already prepared statement
ps.execute();
}
That is, you prepare once and execute many times, each time with different sets of parameters. This allows the driver / database to perform potentially costly operations (such as parsing) only once and then reuse that work. Apart from that, using PreparedStatement
may be interpreted as a hint to the driver that it should cache that statement resources or something because it is going to be used later, but I don't think it will have as much impact as the "prepare once execute many" approach.
Your use of concatenation to add the table names won't disable the optimizations that your JDBC driver does (if any). But anyway, if your code does more of "prepare once execute once" than it does "prepare once execute many", then PreparedStatement might only have a minor performance benefit.
Note that all of the above is highly database / driver dependent. For example, Oracle performs a lot better if you use PreparedStatement
s in the way I have described as "prepare once execute many". And as a last advice, don't forget that you should avoid concatenating parameter values unless you have no other option, for both performance AND SECURITY reasons.