0

是否可以针对 sqlite db 执行具有可变长度子句的批量更新?

val data = Seq(
  Seq(Set(1,2,3), 50),
  Seq(Set(4,5,6,7), 51)
)

NamedDB(symbol).localTx { implicit s: DBSession =>
  sql"""
    update table_a
    set xs=(
      select group_concat(x) from (
        select distinct x from table_b where id in (?)
      )
    ) where id=?
  """.batch(xs.map(_.data): _*).apply()
}

这种默认方法会导致 scalikejdbc 记录参数被设置为对象(警告?),结果是没有应用更新。

我尝试使用参数绑定器,但无法将in (?)参数设置为数组类型,因为 sqlite(及其 JDBC 驱动程序)不支持数组。

另一种方法是更改​​ SQL 文本以?在子句中包含每个值。这对于批量更新是不可能的,因为不同的行具有不同数量的值。

4

1 回答 1

0

我的解决方法是按 in 子句参数的数量对数据进行分组,并为每个参数执行单独的批量更新。

xs.map(_.data).groupBy(_.size - 1).foreach { case (length, data) =>
  NamedDB(symbol).localTx { implicit s: DBSession =>
    val inClauseParams = ("?" * length).mkString(",")
    SQL(
      s"""
       update table_a set xs=(
         select group_concat(x) from (
           select distinct x from table_b where id in ($inClauseParams)
         )
       ) where id=?
     """
    ).batch(data: _*).apply()
  }
}
于 2018-07-01T13:00:56.140 回答