本文探討在使用 GORM 向 postgresql 數據庫插入數據時遇到的問題,特別是錯誤信息 “failed to encode args[3]: unable to encode 1 into text format for varchar (oid 1043): cannot find encode plan” 的解決方法。
問題描述:
在使用 GORM 操作 PostgreSQL 數據庫時,向 menu 表插入數據失敗,報錯信息提示無法將整數 1 編碼為 varchar 類型。
數據庫結構 (DDL):
CREATE TABLE "public"."menu" ( "id" INT4 NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 MINVALUE 1 MAXVALUE 2147483647 START 1 ), "title" VARCHAR(255) COLLATE "pg_catalog"."default", "router" VARCHAR(255) COLLATE "pg_catalog"."default", "state" VARCHAR(255) COLLATE "pg_catalog"."default", "sort" INT4, "icon" VARCHAR(255) COLLATE "pg_catalog"."default", "created_at" TIMESTAMP(6), "updated_at" TIMESTAMP(6), "sid" INT4 NOT NULL DEFAULT 0 ); ALTER TABLE "public"."menu" OWNER TO "postgres";
數據庫連接:
dsn := "host=xxxx user=postgres password=xxxxx dbname=xxxx port=5432 sslmode=disable timezone=asia/shanghai" db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err == nil { db = db }
GORM 結構體定義 (初始):
type menumodel struct { id int `gorm:"column:id" json:"id"` title String `gorm:"column:title" json:"title"` router string `gorm:"column:router" json:"router"` sid int `gorm:"column:sid" json:"sid"` state int `gorm:"column:state" json:"state"` sort int `gorm:"column:sort" json:"sort"` icon string `gorm:"column:icon" json:"icon"` created_at time.time `gorm:"column:created_at;autocreatetime" json:"created_at"` updated_at time.time `gorm:"column:updated_at;autoupdatetime" json:"updated_at"` }
插入操作:
initdb() menu := menumodel{ title: "1", router: "1", sid: 1, state: 1, sort: 1, icon: "1", } db.Create(&menu) fmt.Println(menu.id)
問題分析與解決方案:
錯誤信息指出,state 字段的類型不匹配。數據庫中 state 為 VARCHAR 類型,而 GORM 結構體中定義為 int 類型。 這導致 GORM 嘗試將整數直接轉換為 VARCHAR,引發錯誤。
解決方法:
將 menumodel 結構體中的 state 字段類型修改為 string:
type MenuModel struct { Id int `json:"id"` Title string `json:"title"` Router string `json:"router"` Sid int `json:"sid"` State string `json:"state"` Sort int `json:"sort"` Icon string `json:"icon"` Created_at time.Time `gorm:"autoCreateTime" json:"created_at"` Updated_at time.Time `gorm:"autoUpdateTime" json:"updated_at"` }
同時,gorm:”column:…” 標簽在大多數情況下是冗余的,因為 GORM 會自動映射列名。 簡化后的代碼如上所示。 修改后,數據插入應該能夠成功執行。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END