Anorm中的原子MySQL事务
我编写了一个简单的命中计数器,它使用Anorm更新MySQL数据库表。我希望事务是原子的。我认为最好的方法是将所有SQL字符串连接在一起并执行一个查询,但这在Anorm中似乎是不可能的。相反,我将每个select、update和commit放在单独的行中。这是可行的,但我忍不住想,他们的方式一定更好Anorm中的原子MySQL事务,mysql,scala,anorm,Mysql,Scala,Anorm,我编写了一个简单的命中计数器,它使用Anorm更新MySQL数据库表。我希望事务是原子的。我认为最好的方法是将所有SQL字符串连接在一起并执行一个查询,但这在Anorm中似乎是不可能的。相反,我将每个select、update和commit放在单独的行中。这是可行的,但我忍不住想,他们的方式一定更好 private def incrementHitCounter(urlName:String) { DB.withConnection { implicit connection =>
private def incrementHitCounter(urlName:String) {
DB.withConnection { implicit connection =>
SQL("start transaction;").executeUpdate()
SQL("select @hits:=hits from content_url_name where url_name={urlName};").on("urlName" -> urlName).apply()
SQL("update content_url_name set hits = @hits + 1 where url_name={urlName};").on("urlName" -> urlName).executeUpdate()
SQL("commit;").executeUpdate()
}
}
有人能找到更好的方法吗?使用
with transaction
而不是with connection
如下:
private def incrementHitCounter(urlName:String) {
DB.withTransaction { implicit connection =>
SQL("select @hits:=hits from content_url_name where url_name={urlName};").on("urlName" -> urlName).apply()
SQL("update content_url_name set hits = @hits + 1 where url_name={urlName};").on("urlName" -> urlName).executeUpdate()
}
}
你为什么还要在这里使用交易?这也应该起作用:
private def incrementHitCounter(urlName:String) {
DB.withConnection { implicit connection =>
SQL("update content_url_name set hits = (select hits from content_url_name where url_name={urlName}) + 1 where url_name={urlName};").on("urlName" -> urlName).executeUpdate()
}
}