亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

插入 postgresql 十進制字段失敗,出現錯誤“無法將 {125.00} 轉換為 Int2”

插入 postgresql 十進制字段失敗,出現錯誤“無法將 {125.00} 轉換為 Int2”

Go
LEATH 2023-01-03 15:36:01
我對 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 數據類型是什么?謝謝
查看完整描述

1 回答

?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

125.00向postgres 類型的列中插入一個值的最簡單方法是numeric在 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.Marshaler和json.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)


查看完整回答
反對 回復 2023-01-03
  • 1 回答
  • 0 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號