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.

    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决