Skip to Content
Course content

191: Connecting to a Database with database/sql

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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/sql package and the github.com/lib/pq driver (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.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.