【问题标题】:Atomic MySQL transactions in AnormAnorm 中的原子 MySQL 事务
【发布时间】:2014-03-16 01:18:12
【问题描述】:

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

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

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

【问题讨论】:

    标签: mysql scala anorm


    【解决方案1】:

    像这样使用withTransaction 而不是withConnection

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

    【讨论】:

      猜你喜欢
      • 2014-02-26
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      相关资源
      最近更新 更多