func NamedExec 有什么问题吗?
时间:2024-03-17
浏览:380
作者:佚名
**sqlx.NamedExec 的字段命名问题** 在使用 sqlx.NamedExec 时,如果传递的第二个参数中字段名称与数据库表中字段名称不一致,则会引发错误。具体来说,如果字段名称包含下划线,则需要使用 JSON 字段名称映射(struct field tag)将下划线转换为连字符。通过添加字段名称映射,sqlx.NamedExec 可以正确识别字段名称,避免错误。
问题内容
go版本:1.14.6
sqlx版本:latest
错误代码如下:
test := Test{
Name: "John",
Age: 30,
Id: "bskdvfjreo018g2c5pqg",
}
// table test has fields: id, name, age
_, err := sqlxdb.DB.NamedExec("NSERT INTO test(name,age,id)VALUES(:Name,:Age,:Id)", &test)
log.Println(err)
// log as follow:
// 2020/08/07 11:49:15 could not find name Name in &sqlx.Test{Id:"bskdvfjreo018g2c5pqg", Name:"John", CreateAt:0, Age:30}
有人知道 namedexec 的第二个参数是否必须传递像“:create_at”这样的值,而不是像“:createat”这样的值?
解决方案
与 jmoiron/sqlx issue 419 一样,检查添加 json 字段名称映射(使用 struct field tag)是否有帮助:
type User struct {
Id int `json:"id"`
Name string `json:"name"`
Bio string `json:"about,omitempty"`
Active bool `json:"active"`
Admin bool `json:"-"`
CreatedAt time.Time `json:"created_at"`
}
然后查看将 &test 传递给 namedexec 是否会导致 namedexec 使用 :created_at 而不是 :createdat
今天关于《func NamedExec 有什么问题吗?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
12.01
热门专题
