Skip to content

Instantly share code, notes, and snippets.

@Goodnessuc
Last active November 13, 2022 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Goodnessuc/f4b47769740e9bdc085e64be22bd132d to your computer and use it in GitHub Desktop.
Save Goodnessuc/f4b47769740e9bdc085e64be22bd132d to your computer and use it in GitHub Desktop.
Database transactions in Go
package main
import (
"context"
"database/sql"
_ "github.com/mattn/go-sqlite3"
"log"
)
func main() {
db, err := sql.Open("sqlite3", "goodnessuc.db") // SQLite
if err != nil {
log.Fatalln(err)
}
// create a context for the transaction
ctx := context.Background()
//begin the transaction
transaction, err := db.BeginTx(ctx, nil)
if err != nil {
log.Println("Error beginning the transaction", err)
}
insert, err := transaction.PrepareContext(ctx, "INSERT INTO accounts (username, balance) VALUES (?, ?)")
insert.Exec("David", 8958)
if err != nil {
err := transaction.Rollback()
if err != nil {
log.Println("Error rolling back transaction on the insertion", err)
}
}
row := transaction.QueryRow("SELECT * FROM accounts WHERE balance=5000")
var (
username string
balance int
)
err = row.Scan(&username, &balance)
if err != nil {
transaction.Rollback()
log.Println("Error querying the row", err)
}
// Commit the changes
err = transaction.Commit()
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment