0

我正在关注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 "$1"

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

4

1 回答 1

0

您可以使用batch update, 如文档中所述:

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`
于 2019-07-15T08:29:44.767 回答