Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Anorm中的原子MySQL事务_Mysql_Scala_Anorm - Fatal编程技术网

Anorm中的原子MySQL事务

Anorm中的原子MySQL事务,mysql,scala,anorm,Mysql,Scala,Anorm,我编写了一个简单的命中计数器,它使用Anorm更新MySQL数据库表。我希望事务是原子的。我认为最好的方法是将所有SQL字符串连接在一起并执行一个查询,但这在Anorm中似乎是不可能的。相反,我将每个select、update和commit放在单独的行中。这是可行的,但我忍不住想,他们的方式一定更好 private def incrementHitCounter(urlName:String) { DB.withConnection { implicit connection =>

我编写了一个简单的命中计数器,它使用Anorm更新MySQL数据库表。我希望事务是原子的。我认为最好的方法是将所有SQL字符串连接在一起并执行一个查询,但这在Anorm中似乎是不可能的。相反,我将每个select、update和commit放在单独的行中。这是可行的,但我忍不住想,他们的方式一定更好

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