import ( "database/sql" "github.com/jmoiron/sqlx" _ "github.com/go-sql-driver/mysql" ) func main(){ db, _ := sqlx.Open("mysql", "user:password@tcp(localhost:3306)/database_name") defer db.Close() name := "John" age := 25 _, err := db.NamedExec("INSERT INTO users (name, age) VALUES (:name, :age)", map[string]interface{}{"name": name, "age": age}) if err != nil { log.Fatal(err) } }
import ( "database/sql" "github.com/jmoiron/sqlx" _ "github.com/lib/pq" ) func main(){ db, _ := sqlx.Open("postgres", "user=user password=password dbname=database_name sslmode=disable") defer db.Close() email := "[email protected]" id := 3 _, err := db.NamedExec("UPDATE users SET email = :email WHERE id = :id", map[string]interface{}{"email": email, "id": id}) if err != nil { log.Fatal(err) } }In both examples, we are using the DB NamedExec function to execute a query that has placeholders. We pass a map of values for these placeholders as an argument, and the function takes care of replacing the placeholders with the provided values before executing the query. The package library used here is sqlx, which extends the standard library's sql package by providing a set of utility functions that make working with databases in Go more pleasant. It includes support for placeholders in queries, which is what we are using in these examples.