Created
February 24, 2024 15:55
-
-
Save TheBigRoomXXL/58bbeab340d9a35400f755c68baa932a to your computer and use it in GitHub Desktop.
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
// 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