mirror of
https://github.com/golang/go
synced 2024-11-24 00:40:12 -07:00
database/sql: add example for DB.Prepare and Tx.Prepare
Change-Id: Ib9272a7713ed7aaf8ad54c4827be8c095763e648 Reviewed-on: https://go-review.googlesource.com/c/go/+/161677 Reviewed-by: Daniel Theophanes <kardianos@gmail.com> Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org> TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
parent
cf99535e21
commit
42cdc26665
@ -163,6 +163,63 @@ func ExampleDB_PingContext() {
|
||||
log.Println(status)
|
||||
}
|
||||
|
||||
func ExampleDB_Prepare() {
|
||||
projects := []struct {
|
||||
mascot string
|
||||
release int
|
||||
}{
|
||||
{"tux", 1991},
|
||||
{"duke", 1996},
|
||||
{"gopher", 2009},
|
||||
{"moby dock", 2013},
|
||||
}
|
||||
|
||||
stmt, err := db.Prepare("INSERT INTO projects(id, mascot, release, category) VALUES( ?, ?, ?, ? )")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer stmt.Close() // Prepared statements take up server resources and should be closed after use.
|
||||
|
||||
for id, project := range projects {
|
||||
if _, err := stmt.Exec(id+1, project.mascot, project.release, "open source"); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ExampleTx_Prepare() {
|
||||
projects := []struct {
|
||||
mascot string
|
||||
release int
|
||||
}{
|
||||
{"tux", 1991},
|
||||
{"duke", 1996},
|
||||
{"gopher", 2009},
|
||||
{"moby dock", 2013},
|
||||
}
|
||||
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer tx.Rollback() // The rollback will be ignored if the tx has been committed later in the function.
|
||||
|
||||
stmt, err := tx.Prepare("INSERT INTO projects(id, mascot, release, category) VALUES( ?, ?, ?, ? )")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer stmt.Close() // Prepared statements take up server resources and should be closed after use.
|
||||
|
||||
for id, project := range projects {
|
||||
if _, err := stmt.Exec(id+1, project.mascot, project.release, "open source"); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func ExampleConn_BeginTx() {
|
||||
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
|
||||
if err != nil {
|
||||
|
Loading…
Reference in New Issue
Block a user