I have the following code in Scala to access a database with JDBC. It works fine, however it uses several mutable variables (var
declarations) because these need to be available in the finally
clause for the JDBC elements to be closed. Can this code be changed to use only immutable variables (val
declarations)?
var connection:Connection = null
var statement:Statement = null
var resultSet:ResultSet = null
try {
val url = "someUrl"
val user = "someUser"
val password = "somePwd"
Class.forName("mySql")
connection = DriverManager.getConnection(url, user, password)
statement = connection.createStatement()
resultSet = statement.executeQuery("SELECT column FROM table")
while ( resultSet.next() ) {
val col = resultSet.getString(1)
println(col)
}
}
catch {
case e:Exception => e.printStackTrace
}
finally {
if (resultSet != null) resultSet.close
if (statement != null) statement.close
if (connection != null) connection.close
}