sqlx allows you to map database rows directly to Go types using struct tags or map keys.
Struct Mapping
Use the db struct tag to map database column names to struct fields. If a column is nullable in the database, use sql.Null* types (e.g., sql.NullString) in your struct to avoid scanning errors.
Named Queries
You can use named parameters (e.g., :first_name) in your SQL. sqlx can resolve these from:
- A
map[string]interface{} - A struct (using the
db tag or lowercase field names) - A slice of structs or maps for batch operations.
Batch Insertions
As of version 1.3.0, sqlx.NamedExec supports passing a slice of structs or a slice of maps ([]map[string]interface{}) to perform batch insertions.
type Person struct {
FirstName string `db:"first_name"`
LastName string `db:"last_name"`
Email string
}
// Using a struct for a named query
err := db.NamedExec(`INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)`, personStruct)
// Batch insert with a slice of structs
personStructs := []Person{{FirstName: "Ardie", ...}, {FirstName: "Sonny", ...}}
db.NamedExec(`INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)`, personStructs)