I was looking at this question Reusing a PreparedStatement multiple times
Let's say I have two versions of code. The first closes the PreparedStatement
after each use, inside the for
loop.
connection.autoCommit(false)
for (int i=0; i<1000; i++) {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1, someValue);
preparedStatement.executeQuery();
preparedStatement.close(); // Close after each use.
}
connection.commit();
connection.close();
In this second example, the PreparedStatement
remains open for repeated use, to be closed later after the for
loop.
connection.autoCommit(false)
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i=0; i<1000; i++) {
preparedStatement.clearParameters();
preparedStatement.setObject(1, someValue);
preparedStatement.executeQuery();
}
preparedStatement.close(); // Close after repeated uses.
connection.commit();
connection.close();
As you can see I do create and close PS in loop or reuse the same PS. I do use postgres and according to documentation
Prepared statements only last for the duration of the current database session. When the session ends, the prepared statement is forgotten
As I understand if I use postgres then two examples above will be handled in the same way because it's executed in the same transaction. So for example in the first code sample with new statement inside the loop , postgres will create single planner for statement and even if we close statement and create new one in loop postgres will reuse cached one because it happens in the same session(transaction) and this cached planner will be deleted only when transaction will be committed(connection.commit()
). Am I right ?