golang解决数据库中null值的问题

转自: http://blog.csdn.net/qq_15437667/article/details/78780945

要点

从数据库读取可能为null值得值时,可以选择使用sql.NULL***来读取;或者使用IFNULL、COALESCE等命令让数据库查询值返回不为”“或者NULL
若需要往数据库中插入null值,则依然可以使用sql.NULL***存储所需的值,然后进行插入NULL值
直接使用sql.NULL***类型容易出现valid遗漏设置等问题,普通int、string与其转换时,请写几个简单的get、set函数

从数据库中读取NULL值

Scan NULL值到string的报错
sql: Scan error on column index 1: unsupported Scan, storing driver.Value type into type *string
Scan NULL值到int的报错
sql: Scan error on column index 1: converting driver.Value type (“”) to a int: invalid syntax

使用sqlNull***,
源码定义如下, (不需要自已定义, import “database/sql”)

type NullInt64 struct {
    Int64 int64
    Valid bool // Valid is true if Int64 is not NULL
}
func (n *NullInt64) Scan(value interface{}) error
func (n NullInt64) Value() (driver.Value, error)

type NullString struct {
    String string
    Valid  bool // Valid is true if String is not NULL
}
func (ns *NullString) Scan(value interface{}) error
func (ns NullString) Value() (driver.Value, error)

实现如下:

type Person struct {
    firstName               string
    lastNullName            sql.NullString
    nullAge                 sql.NullInt64
}

rowNull := db.QueryRow("SELECT first_name, last_name FROM person WHERE first_name='yousa'")
err = rowNull.Scan(&hello.firstName, &hello.lastNullName)
if err != nil {
    fmt.Println(err)
}
fmt.Println(hello)

rowNull1 := db.QueryRow("SELECT first_name, age FROM person WHERE first_name='yousa'")
err = rowNull1.Scan(&hello.firstName, &hello.nullAge)
if err != nil {
    fmt.Println(err)
}
fmt.Println(hello)

猜你喜欢

转载自blog.csdn.net/robertkun/article/details/79157599