登录
首页 >  Golang >  Go问答

在 MySQL 中使用 GORM 插入字节类型会导致“错误 1241:操作数应该包含 1 列”

来源:stackoverflow

时间:2024-03-10 19:09:28 361浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《在 MySQL 中使用 GORM 插入字节类型会导致“错误 1241:操作数应该包含 1 列”》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

我有一个输入为 []byte (密码哈希)的模型,我想使用 gorm:v2 将其保存在 mysql:5.7 中。

// this will work
type modelraw struct {
    bytes   []byte
}

type hash []byte

// this will not work
type modeltyped struct {
    bytes hash
}

func main() {
    // migrate database
    // both tables will have a column `bytes` of type `longblob default:null`
    if err := gormdb.automigrate(&modelraw{}, &modeltyped{}); err != nil {
        panic(err)
    }

    // this works
    mdl1 := &modelraw{bytes: []byte("random-bytes")}
    if err := gormdb.debug().create(mdl1).error; err != nil {
        panic(err)
    }

    // error here
    mdl2 := &modeltyped{bytes: hash("random-bytes")}
    if err := gormdb.debug().create(mdl2).error; err != nil {
        panic(err)
    }
}

上述代码产生以下 gorm 调试输出:

2020/11/06 10:31:29 /go/src/app/main.go:47
[7.715ms] [rows:1] INSERT INTO `model_raws` (`bytes`) VALUES ('random-bytes')

2020/11/06 10:31:29 /go/src/app/main.go:53 Error 1241: Operand should contain 1 column(s)
[0.926ms] [rows:0] INSERT INTO `model_typeds` (`bytes`) VALUES ((114,97,110,100,111,109,45,98,121,116,101,115))
panic: Error 1241: Operand should contain 1 column(s)

演示问题的存储库:https://github.com/iyashi/go-gorm-b​​ytes-test

gorm:v1 中工作,并在 gorm:v2 中崩溃。

gorm 的 automigrate() 将 mysql 表列创建为 longblob null


解决方案


为此,您应该实现一个 driver.valuer 接口:

func (h hash) value() (driver.value, error) {
  return []byte(h), nil
}

然后您输入的数据将按预期与 gorm v2 一起使用。

使用的值必须是字节数组,而不是数字数组。

有人会认为 bytes []byte 等价于 type hash []byte 加上 bytes hash,但显然不是。

尝试一下:

mdl2 := &modeltyped{bytes: []byte(hash("random-bytes"))}

或者也许

mdl2 := &ModelTyped{Bytes: []byte{Hash("random-bytes")}}

另一种可能性是在hash的定义中去掉struct;它似乎导致了额外的“结构化”效果。

好了,本文到此结束,带大家了解了《在 MySQL 中使用 GORM 插入字节类型会导致“错误 1241:操作数应该包含 1 列”》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>