golang 记录Converting NULL问题
2022-10-27 本文已影响0人
東玖零
背景:改了一个老接口,需要加个联表查询,sql语句在dbeaver上测试都是好好的,一执行就报错了,报错如下:
Scan error on column index 15, name "name": converting NULL to string is unsupported
网上有多个解决方案,就搬个砖记录一下:
方法一:
package demo
type User struct {
Id string
FirstName string
LastName string
}
func findUserByEmail(ctx context.Context, email string) {
user := &User{}
row := DbConn.QueryRowContext(ctx, `
SELECT id, COALESCE(first_name, '') as first_name, COALESCE(last_name, '') as last_name
FROM users
WHERE email = $1
`, email)
err := row.Scan(&user.Id, &user.FirstName, &user.LastName)
// ...
}
重点看是个COALESCE(first_name, '') as first_name
方法二:
将结构体对应字段类型设为指针类型,一劳永逸,不用担心json序列化与反序列化问题
type User struct {
Id string
FirstName *string `db:"first_name"`
LastName *string `db:"last_name"`
}
重点是这个FirstName *string db:"first_name"
方法三:
func findUserByEmail(ctx context.Context, email string) {
user := &User{}
var st1 sql.NullString
var st2 sql.NullString
row := DbConn.QueryRowContext(ctx, `
SELECT id, first_name, last_name
FROM users
WHERE email = $1
`, email)
err := row.Scan(&user.Id, &st1, &st2)
user.FirstName = str1
user.LastName = str2
// ...
}
重点是这个var st1 sql.NullString
我选的是方法一,实践很好用。