登录
首页 >  Golang >  Go问答

插入 postgresql 小数字段失败并出现错误“无法将 {125.00} 转换为 Int2”

来源:stackoverflow

时间:2024-04-16 18:00:34 447浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《插入 postgresql 小数字段失败并出现错误“无法将 {125.00} 转换为 Int2”》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

我对 golang 还很陌生。我正在尝试使用网络应用程序 gin-gonic 插入具有数字字段的 postgresql 表。

postgres=# \d user_txns;
                       table "public.user_txns"
   column    |         type          | collation | nullable | default
-------------+-----------------------+-----------+----------+---------
 user_id     | character varying(15) |           | not null |
 txn_code    | smallint              |           | not null |
 description | character varying(64) |           | not null |
 txn_amount  | numeric(15,4)         |           | not null |
 txn_type    | smallint              |           | not null |
 voucher     | character varying(16) |           |          |

我正在使用 jackc pgxpool 插入到表中,如下所示。

109 ▏ sql := `insert into user_txns values ($1,$2, $3, $4, $5)`
▎ 110 ▏ _, err = tx.exec(context.background(), sql,
▎ 111 ▏ ▏ ▏ ▏ ▏ ▏ claims["phone"],
▎ 112 ▏ ▏ ▏ ▏ ▏ ▏ recharge,
▎ 113 ▏ ▏ ▏ ▏ ▏ ▏ "user recharge",
▎ 114 ▏ ▏ ▏ ▏ ▏ ▏ recharge.amount,
▎ 115 ▏ ▏ ▏ ▏ ▏ ▏ credit,
▎ 116 ▏ )
▎ 117 ▏ if err != nil {
▎ 118 ▏ ▏ c.json(http.statusinternalservererror, gin.h{"msg": err.error()})
▎ 119 ▏ ▏ return
▎ 120 ▏ },

有效负载是一个具有以下结构的 json 请求:

{
  "amount": 125.00 
}

我将请求解组到如下定义的结构中。

type Recharge struct {
  Amount string `json:"amount" binding:"required"`
}

插入失败并出现错误

"msg": "无法将 {125} 转换为 int2"

用于插入小数字段的正确 golang 数据类型是什么?

谢谢


正确答案


将像 125.00 这样的值插入 numeric 类型的 postgres 列中的最简单方法是在 go 中使用 float 类型。这是开箱即用的,因此不需要实现任何类型的自定义接口。

例如:

create table t (
    id serial primary key
    , amount numeric(15,4) not null
    -- ...
);
data := []byte(`{"amount": 125.00}`)
var obj struct {
    amount float64 `json:"amount"`
}
if err := json.unmarshal(data, &obj); err != nil {
    panic(err)
}

_, err := db.exec(`insert into t (amount) values ($1)`, obj.amount)

但是,浮点类型可能会出现舍入误差,因此存储货币金额的常见做法是使用表示以美分为单位的整数。例如。 125.00 变为 12500。这也是开箱即用的。

例如:

create table t (
    id serial primary key
    , amount int8 not null
    -- ...
);
data := []byte(`{"amount": 12500}`)
var obj struct {
    amount int64 `json:"amount"`
}
if err := json.unmarshal(data, &obj); err != nil {
    panic(err)
}

_, err := db.exec(`insert into t (amount) values ($1)`, obj.amount)

如果您想使用 pgtype.Numeric 在数据库中存储和检索金额,那么您必须做一些额外的工作,因为 pgtype.numeric 不知道如何编码/解码 json 125.00/ “125.00” 值。

您可以做的一件事是声明自定义结构类型,将其嵌入 pgtype.numeric 类型,然后让自定义结构类型实现 json.marshalerjson.unmarshaler 接口。

例如:

create table t (
    id serial primary key
    , amount numeric(15,4) not null
    -- ...
);
type mynumeric struct {
    pgtype.numeric
}

func (n *mynumeric) unmarshaljson(data []byte) error {
    var s json.number
    if err := json.unmarshal(data, &s); err != nil {
        return err
    }
    return n.numeric.set(s.string())
}

func (n mynumeric) marshaljson() ([]byte, error) {
    var f float64
    if err := n.numeric.assignto(&f); err != nil {
        return nil, err
    }
    return []byte(strconv.formatfloat(f, 'f', -1, 64)), nil
}
data := []byte(`{"amount": 125.00}`)
var obj struct {
    Amount MyNumeric `json:"amount"`
}
if err := json.Unmarshal(data, &obj); err != nil {
    panic(err)
}

_, err := db.Exec(`INSERT INTO t (amount) VALUES ($1)`, obj.Amount)

好了,本文到此结束,带大家了解了《插入 postgresql 小数字段失败并出现错误“无法将 {125.00} 转换为 Int2”》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>