将动态变量传递到 INSERT INTO 查询时,Scala doobie 语法错误位于或接近“$1”

Scala doobie syntax error at or near "$1" when pass dynamical vars into INSERT INTO query

我正在学习 doobie 的官方教程。

这是我的代码:

import doobie._
import doobie.implicits._
import doobie.util.ExecutionContexts
import cats._
import cats.data._
import cats.effect.IO
import cats.implicits._

// We need a ContextShift[IO] before we can construct a Transactor[IO]. The passed ExecutionContext
// is where nonblocking operations will be executed. For testing here we're using a synchronous EC.
implicit val cs = IO.contextShift(ExecutionContexts.synchronous)

// A transactor that gets connections from java.sql.DriverManager and executes blocking operations
// on an our synchronous EC. See the chapter on connection handling for more info.
val xa = Transactor.fromDriverManager[IO](
  "org.postgresql.Driver",     // driver classname
  "jdbc:postgresql:world",     // connect URL (driver-specific)
  "postgres",                  // user
  "",                          // password
  ExecutionContexts.synchronous // just for testing
)

val y = xa.yolo
import y._


val drop =
  sql"""
    DROP TABLE IF EXISTS person
  """.update.run

val create =
  sql"""
    CREATE TABLE person (
      id   SERIAL,
      name VARCHAR NOT NULL UNIQUE,
      age  SMALLINT
    )
  """.update.run

然后我 运行 并创建表: (drop, create).mapN(_ + _).transact(xa).unsafeRunSync

上面的所有内容都有效,并且与官方文档中的一样。

下面是我自己的代码:

val first: String = "(1, 'John', 31)" 
val second: String = "(2, 'Alice', 32)"

sql"""insert into person (id, name, age) VALUES $first, $second""".update.quick.unsafeRunSync

我也试过:

sql"""insert into person (id, name, age) VALUES $first, $second""".update.run.transact(xa).unsafeRunSync

然而他们都给我:

org.postgresql.util.PSQLException: ERROR: syntax error at or near ""

如何在 INSERT INTO 中动态传递多个(可能超过 2 个)值?

您可以使用batch update,如doc所述:

type PersonInfo = (Int, String, Int)

def insertMany(ps: List[PersonInfo]): ConnectionIO[Int] = {
  val sql = "insert into person (id, name, age) values (?, ?, ?)"
  Update[PersonInfo](sql).updateMany(ps)
}

// Some rows to insert
val data = List[PersonInfo](
  (1,"John", 31),
  (2,"Alice", 32)
)

// To use `quick` see doc https://tpolecat.github.io/doobie/docs/07-Updating.html#setting-up
insertMany(data).quick.unsafeRunSync

// or
insertMany(data).transact(xa) // where `xa` is your `Transactor`