In Go, you can handle errors and exceptions when executing SQL queries by utilizing the database/sql package's error handling features. Here's a step-by-step guide on how to handle them effectively:
import (
"database/sql"
"fmt"
"log"
)
dsn := "<your-database-connection-string>"
db, err := sql.Open("driver-name", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
Note: Replace driver-name
with the appropriate SQL driver package, such as "postgres" for PostgreSQL or "mysql" for MySQL.
query := "SELECT * FROM table_name"
rows, err := db.Query(query)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var column1 string
var column2 int
// Declare other variables for columns as needed
err = rows.Scan(&column1, &column2)
if err != nil {
log.Fatal(err)
}
// Process the fetched data
fmt.Println(column1, column2)
}
if rows.Err() != nil {
log.Fatal(rows.Err())
}
Additionally, the error instance returned by sql.Open
, db.Query
, rows.Next
, rows.Scan
, and rows.Err
provides more information about the specific error occurred. Therefore, you can customize your error handling based on the specific error type or message received.
By following these steps, you can effectively handle errors and exceptions when executing SQL queries in Go and ensure smooth database operations.