dongwenhui8900 2019-07-26 01:49 采纳率: 0%
浏览 1584

如何将字符串插入jsonb类型postgres?

我有一个函数,它为批处理插入到Postgres生成一个准备好的语句,在这里我试图将字符串插入Postgres中的jsonb类型。

我的结构:

type struct1 struct {
id int
comment string
extra string
}

我的表模式如下所示:

create table deal (
id bigserial,
comment varchar(75),
extra jsonb
)

我想将[]struct 1转储到Postgres DB“Deal”。

生成准备语句的函数如下所示:

func BulkInsert(str []struct1, ctx context.Context) string {
    log.Debug("inserting records to DB")
    query := fmt.Sprintf(`insert into deal (%s) values `, strings.Join(dbFields, ","))
    var numFields = len(dbFields)
    var values []interface{}
    for i, database := range str {
        values = append(values, database.Comment,`'`+database.Extra+`'`)
        n := i * numFields
        query += `(`
        for j := 0; j < numFields; j++ {
            query += `$` + strconv.Itoa(n+j+1) + `,`
        }
        query = query[:len(query)-1] + `),`
    }
    query = query[:len(query)-1]
        return query

预期的结果应该是:我能够将字符串插入json,或者可以说将字符串转换为json并转储。

但真实结果是: could not save batch: pq: invalid input syntax for type json"

  • 写回答

1条回答 默认 最新

  • dptiq46022 2019-07-26 03:05
    关注

    Function of json_build_array('exp1'::Text, 'exp2'::Text) may help you.

    return json object: {'exp1', 'exp2'}

    And extract the values just use operator ->><index> like ->>1 to get 'exp2'.

    If you just want to insert into database, function of to_json('any element') should also works, which can convert any element to a json object.

    And you can get more funtions about json(jsonb) in postgres document.

    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程