本文介绍了Anorm 中的原子 MySQL 事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我编写了一个简单的计数器,它使用 Anorm 更新 MySQL 数据库表.我希望事务是原子的.我认为最好的方法是将所有 SQL 字符串连接在一起并执行一个查询,但是 Anorm 似乎无法做到这一点.相反,我将每个选择、更新和提交放在不同的行上.这有效,但我不禁认为他们必须是更好的方法.

I have written a simple hit counter, that updates a MySQL database table using Anorm. I want the transaction to be atomic. I think that the best way would be to join all of the SQL strings together and do one query, but this doesn't seem to be possible with Anorm. Instead I have placed each select, update and commit on separate lines. This works but I can't help thinking that their must be a better way.

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()
  }
}

谁能找到更好的方法来做到这一点?

Can anyone see a better way to do this?

推荐答案

使用 withTransaction 而不是 withConnection 像这样:

Use withTransaction instead of withConnection like this:

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()
  }
}

你为什么要在这里使用交易?这也应该有效:

And why would you even use a transaction here? This should work as well:

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()
  }
}

这篇关于Anorm 中的原子 MySQL 事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 21:55