gpt4 book ai didi

sql - 玩Anorm和SQL连接

转载 作者:行者123 更新时间:2023-12-01 14:59:34 25 4
gpt4 key购买 nike

Play 2.0 in Scala with anorm framework提供了两种与数据库交互的方法:

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 时都会获取并关闭连接。

为什么这两种方法每次都创建和关闭连接?这不是一个昂贵的过程吗?

最佳答案

em...没有问题,因为我们可以从连接池中检索连接。所以 close() 方法只是将连接返回到池中,并没有真正关闭。

关于sql - 玩Anorm和SQL连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13882947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com