You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang插入PostgreSQL numeric字段报错‘无法转换为Int2’,求正确数据类型

问题分析与解决方案

错误根源

你当前的报错不是numeric字段的类型问题,而是参数传递顺序错误:你的INSERT语句参数顺序对应表的user_id, txn_code, description, txn_amount, txn_type字段,但你把整个recharge结构体传给了txn_code(smallint类型)的位置,pgx无法将结构体转换为Int2,因此抛出cannot convert {125} to Int2错误。

PostgreSQL numeric字段的正确Go类型

针对PostgreSQL的numeric(15,4)字段,可根据场景选择以下Go类型:

  • float64:适合对精度要求不高的场景,使用简单,但存在浮点数精度丢失风险。
  • decimal.Decimal(来自github.com/shopspring/decimal库):金额场景的最佳选择,完全避免精度丢失,pgx原生支持该类型的转换。
  • string:若JSON请求中的金额是字符串格式(如"125.00"),可直接传递string类型,pgx会自动转换为numeric,但需确保字符串是合法数字格式。

修正后的代码示例

首先修正参数顺序,将recharge结构体替换为txn_code对应的数值(比如充值对应的业务编码):

// 假设充值对应的txn_code为1
const TxnCodeRecharge = 1

sql := `INSERT INTO user_txns (user_id, txn_code, description, txn_amount, txn_type) VALUES ($1,$2, $3, $4, $5)`
_, err = tx.Exec(context.Background(), sql,
    claims["phone"],
    TxnCodeRecharge, // 这里传入txn_code的数值,而非整个recharge结构体
    "User recharge",
    recharge.Amount, // 根据选择的类型调整,比如decimal.Decimal或float64
    credit,
)

如果选择使用高精度的decimal类型,调整结构体定义:

import "github.com/shopspring/decimal"

type Recharge struct {
    Amount decimal.Decimal `json:"amount" binding:"required"`
}

此时Gin会自动将JSON中的125.00解析为decimal.Decimal类型,直接传入即可正确插入到numeric字段。

内容的提问来源于stack exchange,提问作者Mopparthy Ravindranath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:24:27