In Go, you can implement error handling for database operations by utilizing the built-in error handling features along with the database/sql package. Here's a general approach:
import (
"database/sql"
_ "github.com/go-sql-driver/mysql" // Import the database driver for your specific database
)
func main() {
db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname")
if err != nil {
// Handle the error
log.Fatal(err)
}
defer db.Close()
// Database operations...
}
// Executing a query
result, err := db.Exec("INSERT INTO users (name, email) VALUES (?, ?)", "John Doe", "[email protected]")
if err != nil {
// Handle the error
log.Fatal(err)
}
// Executing a prepared statement
stmt, err := db.Prepare("UPDATE users SET name = ? WHERE id = ?")
if err != nil {
// Handle the error
log.Fatal(err)
}
defer stmt.Close()
result, err := stmt.Exec("Jane Smith", 1)
if err != nil {
// Handle the error
log.Fatal(err)
}
// Returning the error to the caller
func createUser(name, email string) error {
_, err := db.Exec("INSERT INTO users (name, email) VALUES (?, ?)", name, email)
if err != nil {
return fmt.Errorf("failed to create user: %w", err)
}
// Success
return nil
}
// Logging the error
result, err := db.Exec("DELETE FROM users WHERE id = ?", 1)
if err != nil {
log.Println("failed to delete user:", err)
}
// Retry operation
for retries := 0; retries < maxRetries; retries++ {
result, err := db.Exec("UPDATE users SET name = ? WHERE id = ?", name, id)
if err != nil {
log.Println("failed to update user:", err)
continue // Retry
}
// Success, exit loop
break
}
By incorporating these practices, you can effectively handle errors in your Go code while performing database operations.