将Golang JSON存储到Postgresql中

编程入门 行业动态 更新时间:2024-10-21 06:00:37
本文介绍了将Golang JSON存储到Postgresql中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在数据库中存储一个带有JSON字段的结构.

I want to store a certain struct into my database that has a JSON field within it.

type Comp struct { CompId int64 `db:"comp_id" json:"comp_id"` StartDate time.Time `db:"start_date" json:"start_date"` EndDate time.Time `db:"end_date" json:"end_date"` WeeklySchedule json.RawMessage `db:"weekly_schedule" json:"weekly_schedule"` }

该表的架构为:

CREATE TABLE IF NOT EXISTS Tr.Comp( comp_id SERIAL, start_date timestamp NOT NULL, end_date timestamp NOT NULL, weekly_schedule json NOT NULL, PRIMARY KEY (comp_id) );

我在项目中使用sqlx和lib/pq驱动程序,并且不会执行以下操作.相反,它惊慌地说有一个nil指针. DB是全局*sqlx.DB结构

I am using sqlx and lib/pq driver in my project and the following will not execute. Instead it panics saying there is a nil pointer. DB is a global *sqlx.DB struct

tx := DB.MustBegin() compFixture := Comp{ StartDate: time.Now(), EndDate: time.Now().AddDate(1, 0, 0), WeeklySchedule: json.RawMessage([]byte("{}")), } _, err = tx.NamedExec( `INSERT INTO Tr.Comp(comp_id, start_date, end_date, weekly_schedule) VALUES (DEFAULT, :start_date, :end_date, :weekly_schedule) RETURNING comp_id;`, compFixture) if err != nil { t.Fatal("Error creating fixture.", err) }

当我从架构和固定装置中删除weekly_schedule时,一切运行正常.但是由于某种原因,当包含此字段时,程序会出现紧急情况.关于如何在数据库架构和Go结构中定义weekly_schedule字段的任何想法?

When I remove weekly_schedule from the schema and fixture things run fine. But for some reason, the when this field is included, the program panics. Any idea as to how I should define the weekly_schedule field in both my DB schema and Go struct?

推荐答案

sqlx在github/jmoiron/sqlx/types中具有类型JSONText,它将满足您的需求

sqlx has a type JSONText in github/jmoiron/sqlx/types that will do what you need

doc (针对JSONText)

doc for JSONText

更多推荐

将Golang JSON存储到Postgresql中

本文发布于:2023-10-18 11:03:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504052.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Golang   JSON   Postgresql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!