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")
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?