【问题标题】:Using go's sqlx to insert record in postgres table with automatic ID generation使用 go 的 sqlx 在 postgres 表中插入记录并自动生成 ID
【发布时间】:2020-05-05 20:46:00
【问题描述】:

我正在使用sqlx 创建一个go api。

我想在名为day 的表中插入一条记录。

对应的go结构如下

type Day struct {
    ID      string         `db:"id" json:"id"`
    Dateday string         `db:"dateday" json:"dateday"`
    Nameday string         `db:"nameday" json:"nameday"`
    Holyday bool           `db:"holyday" json:"holyday"`
}

在创建 Day 的端点中,将通过发布请求接收除 ID 之外的所有字段

我应该使用什么方法与我的数据库进行交互,以便:

a) 创建记录

b) 不需要自己传递ID 并指示postgres 自动生成字段。

建表语句如下:

CREATE TABLE IF NOT EXISTS "day" (
  "id" SERIAL PRIMARY KEY,
  "dateday" date NOT NULL,
  "nameday" varchar(10) NOT NULL,
  "holyday" boolean NOT NULL
);

【问题讨论】:

    标签: postgresql go sqlx


    【解决方案1】:

    我建议重写MarshalJSON 方法,如下所述:

    func (r Day) MarshalJSON() ([]byte, error) {
        root := make(map[string]interface{})
    
        root["dateday"] = r.Dateday
        root["nameday"] = r.Nameday
        root["holyday"] = r.Holyday
        return json.Marshal(root)
    }
    

    参考:https://golang.org/pkg/encoding/json/#example__customMarshalJSON

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多