How do I handle NULL values using database/sql with MySQL?

When working with the database/sql package in Go and MySQL, handling NULL values is crucial, especially when dealing with pointers and types. The Go sql package provides ways to handle these values gracefully.

In Go, you can use nullable types like sql.NullString, sql.NullInt64, etc., to manage NULL database values. These types have a valid field that indicates whether the value is valid or NULL.

Here's an example of how to query a MySQL database while handling NULL values:

package main import ( "database/sql" "fmt" "log" "github.com/go-sql-driver/mysql" ) func main() { // DB setup dsn := "user:password@tcp(127.0.0.1:3306)/dbname" db, err := sql.Open("mysql", dsn) if err != nil { log.Fatal(err) } defer db.Close() // Querying the database var name sql.NullString err = db.QueryRow("SELECT name FROM users WHERE id = ?", 1).Scan(&name) if err != nil { log.Fatal(err) } // Handling NULL value if name.Valid { fmt.Println("User name:", name.String) } else { fmt.Println("User name: NULL") } }

Go MySQL database/sql NULL handling sql.NullString sql.NullInt64