为什么在 Golang 中使用 GORM 操作 PostgreSQL 时无法插入数据?

为什么在 Golang 中使用 GORM 操作 PostgreSQL 时无法插入数据?

本文分析了使用 golang 的 GORM 库操作 postgresql 数据库时,数据插入失败的问题,并提供了相应的解决方案。

问题: 在使用 GORM 向 PostgreSQL 数据库插入数据时,出现错误:“failed to encode args[3]: unable to encode 1 into text format for varchar (oid 1043): cannot find encode plan”。 虽然直接执行 SQL 语句可以成功插入,但 GORM 却失败了。

原因分析: 错误信息提示编码失败,原因在于 GORM 尝试将 int 类型数据写入数据库中定义为 varchar 类型的字段。 这通常发生在 Go 结构体字段类型与数据库表字段类型不匹配的情况下。

数据库表结构 (DDL):

立即学习go语言免费学习笔记(深入)”;

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 );

Go 结构体定义 (初始):

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"` }

解决方案: 将 Go 结构体中 state 字段的类型从 int 修改为 string,使其与数据库表中 state 字段的类型一致。

Go 结构体定义 (修正):

type MenuModel struct {     Id         int       `json:"id"`     Title      string    `json:"title"`     Router     string    `json:"router"`     Sid        int       `json:"sid"`     State      string    `json:"state"` // 修改为 string     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 支持根据字段名自动映射,因此除非需要自定义列名,否则可以省略 gorm:”column:…” 标签,简化代码并提高可读性。 如上所示的修正后的结构体已经去除了冗余的 gorm 标签。

通过以上修改,GORM 应该能够正确地将数据插入到 PostgreSQL 数据库中。 记住保持 Go 结构体字段类型与数据库表字段类型的一致性,以避免类似的类型转换错误。

以上就是

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享