Golang中pg.v4库的插入问题解决方案

Golang中pg.v4库的插入问题解决方案 我正在使用“gopkg.in/pg.v4”包,并定义了以下结构体。

Postgres 表结构 (name text default null, amount integer default null)

type Example1 struct {
TableName     struct{}  `sql:"example_table"`
Name             string    `sql:"name"`
Amount          int         `sql:"amount"`
}
type Example2 struct {
TableName     struct{}  `sql:"example_table"`
Name             string    `sql:"name"`
}

现在,当我使用 Example1 创建一行而不为该行传递任何金额值时,在 postgres 数据库中它会自动将金额填充为 0;但当我使用 Example2 时,金额列保持为 NULL。

我希望使用 Example1,并且如果我不传递任何值,则将金额填充为 NULL。我不希望它自动为金额列填充 0。


更多关于Golang中pg.v4库的插入问题解决方案的实战教程也可以访问 https://www.itying.com/category-94-b0.html

5 回复

好的,谢谢!

更多关于Golang中pg.v4库的插入问题解决方案的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


我看到了这个解决方案,但是当我为 Amount 分配一个整数值时,它提示不能将 int 类型用作 sql.NullInt64。

请查看数据库/sql包中的 sql.Null____ 类型(例如 sql.NullInt64)。

type Example1 struct {
    TableName struct{}   `sql:"example_table"`
    Name sql.NullString  `sql:"name"`
    Amount sql.NullInt64 `sql:"amount"`
}

你不能直接这样写:

e1 := Example1{Name: "test", Amount: 1}

我将 NameAmount 的类型分别设置为 sql.NullStringsql.NullInt64。如果你查看这些类型的文档,会发现它们都是结构体。正因为它们是结构体,所以你必须为它们分配结构体:

e1 := Example1{
    Name: sql.NullString{String: "test", Valid: true},
    Amount: sql.NullInt64{Int64: 1, Valid: true},
}

在pg.v4中,当结构体字段有默认值(int类型的零值0)时,即使数据库列允许NULL,库也会插入零值。要解决这个问题,可以使用指针类型或sql.NullInt64

方案1:使用指针类型

type Example1 struct {
    TableName struct{} `sql:"example_table"`
    Name      string   `sql:"name"`
    Amount    *int     `sql:"amount"` // 改为指针类型
}

// 插入时
amount := 100
example := &Example1{
    Name:   "test",
    Amount: &amount, // 有值时传指针
}

// 要插入NULL时
exampleNull := &Example1{
    Name:   "test",
    Amount: nil, // 不传值或显式设为nil
}

方案2:使用sql.NullInt64

import "database/sql"

type Example1 struct {
    TableName struct{}      `sql:"example_table"`
    Name      string        `sql:"name"`
    Amount    sql.NullInt64 `sql:"amount"` // 使用标准库的Null类型
}

// 插入时
example := &Example1{
    Name: "test",
    Amount: sql.NullInt64{
        Int64: 100,
        Valid: true, // 设为true表示有值
    },
}

// 要插入NULL时
exampleNull := &Example1{
    Name: "test",
    Amount: sql.NullInt64{
        Valid: false, // 设为false表示NULL
    },
}

方案3:使用pg.NullInt(如果pg.v4提供)

import "gopkg.in/pg.v4/types"

type Example1 struct {
    TableName struct{}       `sql:"example_table"`
    Name      string         `sql:"name"`
    Amount    types.NullInt  `sql:"amount"` // 使用pg的Null类型
}

// 插入时
example := &Example1{
    Name: "test",
    Amount: types.NullInt{Int: 100, Valid: true},
}

// 要插入NULL时
exampleNull := &Example1{
    Name:   "test",
    Amount: types.NullInt{Valid: false},
}

推荐使用方案2的sql.NullInt64,因为它是标准库类型,兼容性更好。这样当Amount字段为零值时,数据库会插入NULL而不是0。

回到顶部