简体   繁体   English

通过 Scala Anorm(在 Play Framework 中)将数据插入 PostgreSQL jsonb 列

[英]Inserting data to a PostgreSQL jsonb column via Scala Anorm (in Play Framework)

The data column of PostgreSQL table my_table is of format jsonb . PostgreSQL 表my_tabledata列格式为jsonb I would like to insert a Scala JsObject (or JsValue ), but don't know how to do it!我想插入一个 Scala JsObject (或JsValue ),但不知道该怎么做!

The following code does not compile, because the on function expects json to be a String :以下代码无法编译,因为on期望jsonString

  def add(json: JsObject): Option[Long] = {
    DB.withConnection {
      implicit c =>

        val query = """
             insert into my_table(data)
        values({data});"""

        SQL(query).on(
          "data" -> json
        ).executeInsert()
    }
  }

What is the solution?解决办法是什么?

Use ::jsonb tag at the end of a value. 在值的末尾使用:: jsonb标记。 eg. 例如。

//my scala variables

val jsonDescription: String = "{\"name\":\"ksulr\"}"
val age = 15

//my insert statement
val sql = "INSERT into person(json_description,age) VALUES(?::jsonb,?)"

//prepared statement
val statement = conn.prepareStatement(sql)

//insert values into the sql statement
statement.setString(1,jsonDescription)
statement.setInt(2,age)

statement.executeUpdate()

This will work. 这会奏效。 It worked for me. 它对我有用。 Thats how I inserted into a postgres db column of type jsonb . 这就是我如何插入jsonb类型的postgres db列。

You can use ToStatement converter object: 您可以使用ToStatement转换器对象:

def add(json: JsObject): Option[Long] = {
   DB.withConnection { implicit c =>       
      val query = """insert into my_table(data) values(${data});"""
      SQL(query).executeInsert()
   }
}

implicit object jsObjectStatement extends ToStatement[JsObject] {
    override def set(s: PreparedStatement, index: Int, v: JsObject): Unit = {
      val jsonObject = new PGobject()
      jsonObject.setType("json")
      jsonObject.setValue(Json.stringify(v))
      s.setObject(index, jsonObject)
    }
  }

Borrowing from @KJay_wer, we can use ::jsonb tag with Scala Anorm (Play Framework) too, and convert your JsObject (or other JsValue ) into String :借用@KJay_wer,我们也可以将::jsonb标签与 Scala Anorm(Play Framework)一起使用,并将您的JsObject (或其他JsValue )转换为String

def add(json: JsObject): Option[Long] = {
    DB.withConnection {
      implicit c =>

        val query = """
             insert into my_table (data)
             values ({data}::jsonb);
             """.stripMargin

        SQL(query).on(
          "data" -> json.toString
        ).executeInsert()
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Anorm从PostgreSQL jsonb列解析JSON - Anorm parsing JSON from PostgreSQL jsonb column 如何为play-scala anorm pgsql设置jsonb []的类型 - how to set type for jsonb[] for play-scala anorm pgsql 在播放框架2中使用anorm将对象持久化在postgresql数据库中 - persist object in postgresql database with anorm in a play framework 2 使用Daper.Net和NPGSQL将数据插入PostgreSQL jsonb列 - Inserting data into PostgreSQL jsonb column with Daper.Net and NPGSQL PostgreSQL数字类型和Play的anorm解析器! 斯卡拉2.3 - PostgreSQL numeric type and anorm parser with Play! scala 2.3 在Play框架Scala中配置postgreSQL - Configuring postgreSQL in play framework Scala 哪个是Scala和PostgreSQL的Play框架可用的最佳数据访问选项? - Which is best data access options available for Play framework with Scala and PostgreSQL? 在 postgresql 中的 jsonb[] 类型列中插入数据的正确语法是什么 - What is the correct syntax of inserting the data inside the jsonb[] type column inside postgresql 插入PostgreSql Jsonb列时,字符串操作会引发错误 - String Manipulation throws error while Inserting into PostgreSql Jsonb Column 通过在JSONB列上应用过滤器来查询Postgresql中的数据 - Querying data in postgresql by applying filter on a JSONB column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM