I've been working on a SQL utility and I am trying to set the parameters inside a prepared statement in multiple functions.
To lessen the code, I have a function that returns a prepared statement where all the params are set.
My question is:
Does the connection reference in the configureStatement()
get closed using the try with resources in the query()
? If not how can the code be refactored to close the PreparedStatement
and the Connection
every time?
public void query(String queryString, List<String> queryParams, Consumer<ResultSet> sqlConsumer)
{
try (PreparedStatement preparedStatement = this.configureStatement(queryString, queryParams))
{
sqlConsumer.accept(preparedStatement.executeQuery());
} catch(SQLException exception)
{
exception.printStackTrace();
}
}
private PreparedStatement configureStatement(String query, List<String> queryParams) throws SQLException
{
PreparedStatement preparedStatement = this.getConnection().prepareStatement(query);
for (int i = 0; i < queryParams.size(); ++i)
preparedStatement.setString(i, queryParams.get(i));
return preparedStatement;
}