栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

解决go数据表查询结构体对应字段null问题(sqlx converting NULL to string is unsupported)

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解决go数据表查询结构体对应字段null问题(sqlx converting NULL to string is unsupported)

方法一:将结构体对应字段类型设为指针类型,一劳永逸,不用担心json序列化与反序列化问题

// User 用户结构体(对应mysql表)
type User struct {
	Id         int       `db:"id"`
	Code       *string   `db:"code"`
	NickName   string    `db:"nick_name"`
	Phone      string    `db:"phone"`
	Password   string    `db:"password"`
	CreateTime time.Time `db:"create_time"`
	Sex        int       `db:"sex"`
	Email      string    `db:"email"`
}

例如上述的Code字段,不设置为指针类型的话,查询时mysql里为null的话序列化就会出现“sqlx converting NULL to string is unsupported”,或者在设计表的时候字符串类型设计默认值为空字符串

方法二:将结构体对应字段设置为sql.NullString,另外构建一个结构体在应用使用

// User 用户结构体(对应mysql表)
type User struct {
	Id         int             `db:"id"`
	Code       sql.NullString  `db:"code"`
	NickName   sql.NullString  `db:"nick_name"`
	Phone      sql.NullString  `db:"phone"`
	Password   sql.NullString  `db:"password"`
	CreateTime format.JsonTime `db:"create_time"`
	Sex        int             `db:"sex"`
	Email      sql.NullString  `db:"email"`
}

//应用层使用
type UEntity struct {
	Id         int
	Code       string
	NickName   string
	Phone      string
	Password   string
	CreateTime format.JsonTime
	Sex        int
	Email      string
}

//数据库结构体与应用层使用的结构体转换
func copyValue(user User, uEntity UEntity) UEntity {
	uEntity.Id = user.Id
	uEntity.Code = user.Code.String
	uEntity.NickName = user.NickName.String
	uEntity.Phone = user.Phone.String
	uEntity.Password = user.Password.String
	uEntity.CreateTime = user.CreateTime
	uEntity.Email = user.Email.String
	return uEntity
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/903198.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号