DB:
column: name
value: NULL
Get the record from DB with gorm, then
var name string
if name != nil {
//
}
Got error:
invalid operation: name != nil (mismatched types string and nil)
Yes, nil is using for int type in go, but this case, the value in DB is NULL
but not ""
, so it's necessary to check null
, how to do?
You can also use a pointer to string to map NULL values from the database, but this will create cases where you cannot give values without creating a variable first.
var name *string
if name != nil {
//
}
// but
name = "will not work"
Or you could use the github.com/go-sql-driver/mysql
(or whatever driver you are using) and database/sql
package implementations. You can define your own types based on those if you want to add functionality:
// NullInt64 is an alias for sql.NullInt64 data type
type NullInt64 sql.NullInt64
// NullBool is an alias for sql.NullBool data type
type NullBool sql.NullBool
// NullFloat64 is an alias for sql.NullFloat64 data type
type NullFloat64 sql.NullFloat64
// NullString is an alias for sql.NullString data type
type NullString sql.NullString
// NullTime is an alias for mysql.NullTime data type
type NullTime mysql.NullTime
You should pay your attention on sql types: https://golang.org/pkg/database/sql/#NullString
Just use variable with this type in your select statement:
var yourstr sql.NullString
db.Select("Select your string", &yourstr)
Then you could check if it is valid and if it is not you could assign any value you want:
if !yourstr.Valid{
yourstr.String = ""
}
In gorm also is a function to select NullString:
yourstr := dbmap.SelectNullStr("Select your string")