Introduction
Go SQL rows are not closed when defer rows. This guide provides step-by-step diagnosis and resolution with specific commands and code examples.
Symptoms
Typical symptoms and error messages when this issue occurs:
sql: Rows not closed
rows.Close() not calledObservable indicators: - Application logs show connection or operation failures - Error messages appear in system or application logs - Related dependent services may exhibit cascading failures
Common Causes
- 1.Database connection issues are commonly caused by:
- 2.Incorrect connection string format
- 3.Missing driver registration in init()
- 4.Pool size mismatch with concurrent query load
Step-by-Step Fix
Step 1: Check Current State
go version && go envStep 2: Identify Root Cause
go build -v ./...Step 3: Apply Primary Fix
// Primary fix: update configuration
cfg := Config{
Timeout: 30 * time.Second,
MaxRetry: 3,
LogLevel: "info",
}Apply this configuration and restart the application:
go build && ./applicationStep 4: Apply Alternative Fix (If Needed)
// Alternative fix: use context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
result, err := operation.WithContext(ctx)Monitor database connection metrics after changes: SHOW STATUS LIKE "Threads%";
Step 5: Verify the Fix
After applying the fix, verify with:
go test -v ./pkg/database -run TestConnectionPoolExpected output should show successful operation without errors.
Common Pitfalls
- Scanning NULL values into non-nullable types
- Not closing rows.Rows after iteration
- Using default pool size for high concurrency
Best Practices
- Use context for all database operations
- Close rows immediately after use
- Set connection pool limits based on load
Related Issues
- Go SQL Transaction Deadlock
- Go SQL Null Value Handling Error
- Go SQL Connection Refused