dongxieyou3314 2018-11-27 13:55
浏览 902

如何将JSON数据插入PostgreSQL

I have the json field like blow which I want to store in database

{
      id:          1
      name:        "test entity 1"
      description: "a test entity for some guy's blog"
      status: "passed"
      web_url: "http://localhost:3000"
      jobs: [{
         id:        "1"
         name:      "test1"
         status:    "passed"
        },
        {
         id:        "2"
         name:      "test2"
         status:    "passed"
        },
        {
         id:        "3"
         name:      "test3"
         status:    "failed"
       }]
    }

I proceed with one way like for creating table uses:

CREATE TABLE test3 (id INT PRIMARY KEY, name VARCHAR, description VARCHAR, status VARCHAR, web_url VARCHAR, jobs JSON[]);

and for Inserting data uses:

sqlStatement := `
            INSERT INTO jobs (id, name, description, status, web_url, jobs)
            VALUES ($1, $2, $3, $4, $5, $6)
            ON CONFLICT (id) DO UPDATE
            SET status = $4
            RETURNING id`
        id := 0
        err = database.Db.QueryRow(sqlStatement, y[i].ID, y[i].Name, y[i].Description, y[i].Status, y[i].WebURL, jobsdata).Scan(&id)
        if err != nil {
            panic(err)
        }

But won't work, need help!!

Getting errors:

panic: sql: converting argument $6 type: unsupported type handler.Jobs, a slice of struct

What i want:

postgres=# SELECT * FROM test3;
id |    name       |             description           | status  |       web_url          |                           jobs                           
------+------------------------------------------+--------+---------+----------------------------------------------------------+----------------------------------------------------------
 1 | test entity 1 | a test entity for some guy's blog | passed | https://localhost:3000 | {id: "1",name: "test1", status: "passed"},{id: "2",name: "test2", status: "passed"},{id: "3",name: "test3", status: "failed"}
  • 写回答

2条回答 默认 最新

  • douling1936 2018-11-27 15:22
    关注

    As the error indicates, you're trying to bind the sixth value from an unsupported data type, handler.Jobs. You haven't told us what this type is, but from the error, it's clear that it does not implement the driver.Valuer interface, so it won't work, because it has no way of knowing how to represent that value to the database.

    You'll need to implement that interface, by adding a Value() method to the handler.Jobs type, or use a different data type.

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?