db, err := sqlx.Connect("mysql", "user:password@/database") if err != nil { log.Fatalln(err) } tx, err := db.Beginx() if err != nil { log.Fatalln(err) } _, err = tx.NamedExec("INSERT INTO users (name, age) VALUES (:name, :age)", map[string]interface{}{"name": "John Doe", "age": 30}) if err != nil { log.Fatalln(err) } err = tx.Commit() if err != nil { log.Fatalln(err) }
type User struct { Name string `db:"name"` Age int `db:"age"` } db, err := sqlx.Connect("postgres", "user=postgres password=postgres dbname=testdb sslmode=disable") if err != nil { log.Fatal(err) } tx, err := db.Beginx() if err != nil { log.Fatalln(err) } user := User{Name: "Emily", Age: 25} _, err = tx.NamedExec("INSERT INTO users (name, age) VALUES (:name, :age)", user) if err != nil { log.Fatalln(err) } err = tx.Commit() if err != nil { log.Fatalln(err) }In this example, we define a `User` struct with `db` tags, which is used to map the struct fields to the corresponding column names in the database. We then use `Tx.NamedExec()` to insert a new user by passing in the `User` struct directly as the second argument. Overall, `github.com.jmoiron.sqlx` is a powerful Go package that makes interacting with databases using SQL much simpler and more intuitive.