Last active
November 13, 2022 10:35
-
-
Save goodylili/f4b47769740e9bdc085e64be22bd132d to your computer and use it in GitHub Desktop.
Database transactions in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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