In the previous section, we saw how to create self-closing connections with the loan pattern. This allows us to open connections to the database without having to remember to close them. However, we still have to remember to close any ResultSet
and PreparedStatement
that we open:
// WARNING: Poor Scala code SqlUtils.usingConnection("test") { connection => val statement = connection.prepareStatement( "SELECT * FROM physicists") val results = statement.executeQuery // do something useful with the results results.close statement.close }
Having to open and close the statement is somewhat ugly and error prone. This is another natural use case for the loan pattern. Ideally, we would like to write the following:
usingConnection("test") { connection =>
connection.withQuery("SELECT * FROM physicists") {
resultSet => // process results
}
}
How can we define a .withQuery
method on the Connection
class? We do not...