Java SQL .close() necesary if keep re-instantiating object?

I know that if you create an SQL PreparedStatement or ResultSet, you should use .close() on the resource when you’re finished with it. If however I’m looping and just recreating the PreparedStatement with each iteration, do I still have to call .close() on it during each iteration, or just when I’m finished?

For example, if i have this:

private Connection con;
private String[] queries;
private PreparedStatement stmt;

create connection
fill array queries with 10 queries in it

for (int i = 0; i < 10; i++) {

    stmt = con.prepareStatement(queries[i], Statement.RETURN_GENERATED_KEYS);
    // necessary?

Is it necessary to .close() stmt with each iteration, or should I just do it when loop is complete? Why or why not? Thank you.


You’re creating a new object with each iteration. Each statement you leave open can keep resources open on the database server for longer than necessary. Closing the connection should clean up everything, but JDBC drivers have been known to have bugs where they failed to clean up.

Close them all in a finally block, or use try with resources.