本文探讨使用Go语言和GORM库操作PostgreSQL数据库时遇到的一个问题:尝试向menu表插入数据失败,报错“failed to encode args[3]: unable to encode 1 into text format for varchar (oid 1043): cannot find encode plan”。
数据库表menu的定义如下:
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"; COMMENT ON COLUMN "public"."menu"."title" IS '标题'; COMMENT ON COLUMN "public"."menu"."router" IS '路由'; COMMENT ON COLUMN "public"."menu"."state" IS '状态'; COMMENT ON COLUMN "public"."menu"."sort" IS '排序'; COMMENT ON COLUMN "public"."menu"."icon" IS '图标'; COMMENT ON TABLE "public"."menu" IS '菜单表';
数据库连接代码如下:
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 { // 处理错误 }
对应的Go语言结构体:
type MenuModel struct { ID int `gorm:"column:id"` Title string `gorm:"column:title"` Router string `gorm:"column:router"` Sid int `gorm:"column:sid"` State int `gorm:"column:state"` // 问题所在 Sort int `gorm:"column:sort"` Icon string `gorm:"column:icon"` CreatedAt time.Time `gorm:"column:created_at;autoCreateTime"` UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime"` }
插入数据的代码:
initdb() // 初始化数据库连接 menu := MenuModel{ Title: "1", Router: "1", Sid: 1, State: 1, // 问题所在 Sort: 1, Icon: "1", } db.Create(&menu) fmt.Println(menu.ID)
错误信息提示无法将整数1编码为varchar类型。仔细对比数据库表结构和Go语言结构体定义,发现问题在于MenuModel结构体的State字段类型为int,而数据库表中的state列类型为varchar。 这导致GORM尝试将整数直接插入到varchar列中,引发类型不匹配错误。
解决方法是将MenuModel结构体的State字段类型修改为string:
type MenuModel struct { ID int `gorm:"column:id"` Title string `gorm:"column:title"` Router string `gorm:"column:router"` Sid int `gorm:"column:sid"` State string `gorm:"column:state"` // 修改为string Sort int `gorm:"column:sort"` Icon string `gorm:"column:icon"` CreatedAt time.Time `gorm:"column:created_at;autoCreateTime"` UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime"` }
修改后,GORM将正确地将字符串"1"插入到数据库的state列中。 此外,GORM的标签可以简化,因为GORM会根据字段名自动推断列名。
通过这个修改,应该可以解决数据插入问题。 记住处理gorm.Open函数可能返回的错误。
以上就是为什么使用 GORM 无法将数据插入到 PostgreSQL 数据库中的菜单表?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号