Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
191: Connecting to a Database with database/sql
I want to start this lesson with a snippet of code that looks perfectly fine on the surface. You've got your connection string, you're using the standard library, and you're handling your errors. But when you run this, it crashes immediately with a panic: panic: sql: unknown driver "postgres".
package main
import (
"database/sql"
"fmt"
"log"
)
func main() {
connStr := "user=pqgotest dbname=pqgotest sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
defer db.Close()
fmt.Println("Connected successfully!")
}
The "Unknown Driver" Mystery
If you're looking at that code and thinking, "But I installed the driver with go get!", you're not alone. This is one of the most confusing parts of Go's database design for newcomers.
The database/sql package is intentionally generic. It provides a consistent set of interfaces so that you can switch from PostgreSQL to MySQL or SQLite without rewriting your entire business logic. However, database/sql doesn't actually know how to talk to any specific database; it needs a "driver" to do the heavy lifting.
The fix is a "blank import." You need to import the driver package for its side effects (specifically, its init() function, which registers the driver with the sql package), but since you don't call any functions from the driver package directly, Go's compiler will complain if you import it normally. We use the underscore _ to tell Go: "I need this package's initialization code, but I won't be calling its functions directly."
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq" // This is the magic line
)
Why a Lazy Open Isn't Enough
Now, let's say you add the import and run the code again. It prints "Connected successfully!" and exits. You might think everything is great, but here is the catch: sql.Open doesn't actually connect to the database.
I can put a completely fake password or a non-existent IP address in my connection string, and sql.Open will still return nil for the error. It simply validates the arguments. It's "lazy." The actual connection is only established when you first try to use the database.
In a real production app, you don't want to find out your database credentials are wrong five minutes after the server starts—you want to know immediately. To fix this, we use db.Ping(). This forces the driver to actually establish a connection and verify the server is reachable.
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
// Verify the connection is actually alive
err = db.Ping()
if err != nil {
log.Fatalf("Database unreachable: %v", err)
}
Managing the Connection Pool
One last thing I want you to keep in mind: *sql.DB is not a single connection. It is a connection pool. When you call a query, Go grabs a connection from the pool, uses it, and then puts it back.
You should almost never open and close the database for every single function call. That would be a performance nightmare because establishing a TCP connection is expensive. Instead, you open the *sql.DB object once when your application starts and pass that object (or a pointer to it) throughout your app. Use defer db.Close() in your main function to ensure the pool is cleaned up when the program shuts down.
📋 Practical Task
Exercise: Building a Database Connection Health Checker
Your task is to create a small CLI utility that validates a database connection string. This will simulate a "health check" tool used in deployment pipelines.
Requirements:
- Import the
database/sqlpackage and thegithub.com/lib/pqdriver (using a blank import). - Create a function called
CheckConnection(driverName, connectionString string) error. - Inside that function, attempt to open the database and immediately
Ping()it. - In
main, define a connection string (you can use a local Postgres instance or a dummy string to test the failure case). - If the connection is successful, print
"Database Status: ONLINE". If it fails, print"Database Status: OFFLINE"followed by the specific error returned by the driver.
There are no comments for now.