簡體   English   中英

嘗試從 h2 數據庫中檢索 json 數據時出錯

[英]Error when trying to retrieve json data from h2 database

我有下表定義

create table samples (
   channel text,
   eventType text,
   data json NOT NULL
);

我還嘗試將data列定義為clobtextjava_objectvarcharother 我正在使用以下 API 在 h2 中插入數據:

def insert(sample: Sample): Unit = DB localTx { implicit session =>
    val propertiesJson = new PGobject()
    propertiesJson.setType("json")
    propertiesJson.setValue(sample.properties.toJson.toString)
    sql"""
         insert into samples
         (channel,eventType,data) values (${sample.channel}, ${sample.eventType},$propertiesJson )
    """.update().apply()

}

這個是檢索數據

  def find(channel: String): List[Sample] = DB readOnly { implicit session =>
    sql"""
     select * from samples where channel = $channel
     """.map(rs => {

     Sample(
       channel = rs.string("channel"),
       properties = rs.string("data").parseJson.convertTo[Map[String, String]],
       eventType = rs.string("eventType")
     )
    }
    ).list().apply()
   }

我正在使用sprayscalikejdbc驅動程序進行隱式轉換。

根據data列的數據類型,我會遇到不同的錯誤。

  • 對於CLOBVARCHARTEXTJAVA_OBJECT :我可以在 h2 中插入數據,但是在嘗試檢索時我得到了

    spray.json.JsonParser$ParsingException: Unexpected character 'a' at input index 0 (line 1, position 1), expected JSON Value: aced00057372001c6f72672e706f737467726573716c2e7574696c2e50476f626a656374f903de2682bdcb3b0200024c0004747970657400124c6a6176612f6c616e672f537472696e673b4c000576616c756571007e000178707400046a736f6e74001f7b2270726f7041223a2276616c41222c2270726f7042223a2276616c42227d
  • 對於JSON 我什至無法將數據插入 h2。 我越來越

    Caused by: org.h2.jdbc.JdbcSQLDataException: Data conversion error converting "OTHER to JSON" [22018-200] at org.h2.message.DbException.getJdbcSQLException(DbException.java:457) at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)... 114 more

使用JSON時,我也嘗試過這里提出的這種format json指令

另請參見 json 文字語法。 映射到字節[]。 要在 PreparedStatement 中使用 java.lang.String 設置 JSON 值,請使用格式 JSON 數據格式 (INSERT INTO TEST) JSON) 沒有數據格式的 VARCHAR 值將轉換為 JSON 字符串值。

但錯誤仍然相同。

那么有什么想法嗎? 如何從 h2 數據庫中成功插入和檢索 JSON 數據? 我的方法有什么問題嗎?

我對 Scala 不熟悉,但你絕對不能將PGobject與 H2 一起使用,這個 class 是特定於 PgJDBC 的。 要將 JSON 值傳遞給 H2,您需要使用純字節數組(Java 中的byte[] ,Scala 中的Array[Byte] ); 傳遞的數組應包含 UTF-8、UTF-16 或 UTF-32 編碼的 JSON 文本。 如果您願意,您也可以使用java.lang.String ,但它需要在參數后的 SQL 中使用FORMAT JSON子句。

To read a JSON value from H2 it would be better to use ResultSet.getBytes(…) in Java/JDBC and WrappedResultSet.bytes(…) in ScalikeJDBC, it will return byte array with JSON text in UTF-8 encoding. 目前您正在使用string(…)方法,它至少應該適用於 H2 1.4.200,但這種行為沒有記錄在案,並且可能會在未來的版本中更改。

這些建議適用於 H2 的內置 JSON 數據類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM