使用anorm框架在Scala中播放2.0提供了两种与数据库交互的方法:
def withConnection[A](name: String)(block: Connection => A): A = {
val connection = new AutoCleanConnection(getConnection(name))
try {
block(connection)
} finally {
connection.close()
}
}
/**
* Execute a block of code, in the scope of a JDBC transaction.
* The connection and all created statements are automatically released.
* The transaction is automatically committed, unless an exception occurs.
*
* @param name The datasource name.
* @param block Code block to execute.
*/
def withTransaction[A](name: String)(block: Connection => A): A = {
withConnection(name) { connection =>
try {
connection.setAutoCommit(false)
val r = block(connection)
connection.commit()
r
} catch {
case e => connection.rollback(); throw e
}
}
}
现在我很清楚,每次调用时,withConnection都会获取并关闭连接。
为什么两种方法每次都创建和关闭连接?这不是一个昂贵的过程吗?
答案 0 :(得分:2)
em ...没有问题,因为我们可以从连接池中检索连接。 所以close()方法只返回到池的连接,而不是实际关闭。