For clarification: I know that it’s the right thing to create the PreparedStatement outside the loop. I’ve asked this question just out of curiosity.
Let’s assume that I’m creating a PreparedStatement inside a loop with always the same SQL query.
final String sql = "INSERT INTO ...";
while (condition) {
...
PreparedStatement statement = connection.prepareStatement(sql);
// Fill values of the prepared statement
// Execute statement
...
}
Is this useless since the PreparedStatement object is always created anew? Or does the underlying database recognise that it’s always the same SQL query with which the PreparedStatement is created and reuses it?
Some drivers do cache prepared statements, yes. For example, skim this Oracle documentation:
http://docs.oracle.com/cd/B10501_01/java.920/a96654/stmtcach.htm
I don’t believe there’s anything that requires this to be true for all drivers, although certainly it seems like a likely feature of many JDBC drivers. It sounds like MySQL might not do this:
How to use MySQL prepared statement caching?
That said, if you really want to use prepared statements efficiently, it seems like hanging on to an instance of a prepared statement that you use on each loop iteration makes a lot more sense.