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

时间:2019-07-15 08:19:22

标签: postgresql scala doobie

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

如何动态传递INSERT INTO中的多个(可能有两个以上)值?

1 个答案:

答案 0 :(得分:0)

您可以使用doc中所述的 "dependencies": { "@agm/core": "~1.0.0-beta.5", "@angular/animations": "~7.2.0", "@angular/common": "~7.2.0", "@angular/compiler": "~7.2.0", "@angular/core": "~7.2.0", "@angular/forms": "~7.2.0", ... },

batch update