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
?