Skip to content

Instantly share code, notes, and snippets.

@TheBigRoomXXL
Created February 24, 2024 15:55
Show Gist options
  • Save TheBigRoomXXL/58bbeab340d9a35400f755c68baa932a to your computer and use it in GitHub Desktop.
Save TheBigRoomXXL/58bbeab340d9a35400f755c68baa932a to your computer and use it in GitHub Desktop.
// Insert using sql.DB with transaction
func InsertPage(db *sql.DB, url string, content string) error {
// Open transaction
tx, err := db.Begin()
if err != nil {
return err
}
// Prepare statement
stmt, err := tx.Prepare("INSERT INTO pages (url, content) values(?, ?)")
if err != nil {
rollbackErr := tx.Rollback()
if rollbackErr != nil {
return err
}
return err
}
defer stmt.Close()
// Exacute statement
_, err = stmt.Exec(url, content)
if err != nil {
rollbackErr := tx.Rollback()
if rollbackErr != nil {
return err
}
return err
}
// Finish transaction
err = tx.Commit()
if err != nil {
rollbackErr := tx.Rollback()
if rollbackErr != nil {
return err
}
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment