Go Sql Rows Close
In this tutorial, you'll learn about Go SQL Rows: Not Closed Causes Connection Leak. We cover key concepts, practical examples, and best practices.
SQL rows.Close() -- Close database Rows after iterating to prevent connection pool exhaustion.
The Problem
sql.Rows holds a database connection open until you Close it. Forgetting to close rows causes connection pool exhaustion. Always defer rows.Close().
Wrong
rows, err := db.Query("SELECT id, name FROM users")
if err != nil { log.Fatal(err) }
for rows.Next() { rows.Scan(&u.ID, &u.Name) }
Output:
// If Scan fails, rows not consumed, connection stays open
Right
rows, err := db.Query("SELECT id, name FROM users")
if err != nil { return err }
defer rows.Close()
for rows.Next() {
if err := rows.Scan(&u.ID, &u.Name); err != nil { return err }
}
return rows.Err()
Output:
// Even on error, rows.Close() is called via defer
Prevention
- Always defer rows.Close() immediately after db.Query()
- Always check rows.Err() after the loop
- rows.Close() is safe to call multiple times
- For QueryRowContext, no Close needed
- Do not close rows before the loop if you need results
Common Mistakes with sql rows close
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro