Safer JDBC connections with the loan pattern
We have already seen how to connect to a JDBC database and send statements to the database for execution. This technique, however, is somewhat error prone: you have to remember to close statements; otherwise, you will quickly run out of memory. In more traditional imperative style, we write the following try-finally block around every connection:
// WARNING: poor Scala code val connection = DriverManager.getConnection(url, user, password) try { // do something with connection } finally { connection.close() }
Scala, with first-class functions, provides us with an alternative: the loan pattern. We write a function that is responsible for opening the connection, loaning it to the client code to do something interesting with it, and then closing it when the client code is done. Thus, the client code is not responsible for closing the connection any more.
Let's create a new SqlUtils
object with a usingConnection
method that leverages the loan pattern...