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

如何将字符串插入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 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条