Opening a Connection
Connect to a database.
Opening a Connection is a free Go Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The database/sql Package
Gos standard database/sql package provides a generic, database-agnostic API. You pair it with a driver for your specific database, like PostgreSQL or MySQL.
- One API, many databases
- Built-in connection pooling
- Safe parameterized queries
Importing a Driver
The driver registers itself via a blank import. The underscore means you import it only for its side effect, registration, not to call it directly.
import (
"database/sql"
_ "github.com/lib/pq"
)sql.Open
sql.Open takes a driver name and a data source name (DSN). It does not actually connect yet; it just prepares the pool.
db, err := sql.Open("postgres", "postgres://user:pass@localhost/mydb?sslmode=disable")
if err != nil {
log.Fatal(err)
}db Is a Pool
The returned *sql.DB is not a single connection, it is a pool of connections, safe for concurrent use by many goroutines. Open it once and share it across your app.
Verify with Ping
Because Open is lazy, use Ping to actually establish a connection and confirm the database is reachable and credentials are valid.
if err := db.Ping(); err != nil {
log.Fatal("cannot reach db:", err)
}Closing the Pool
Defer db.Close() in your main or setup function. You rarely close per query, only when the whole application shuts down.
defer db.Close()Pool Tuning
Control the pool with SetMaxOpenConns, SetMaxIdleConns, and SetConnMaxLifetime. These prevent exhausting the database and recycle stale connections.
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(5 * time.Minute)A Runnable In-Memory Example
Real drivers need a network database, so this runnable example shows the same lifecycle with a simulated open and ping using only the standard library types.
package main
import (
"errors"
"fmt"
)
type DB struct{ dsn string }
func Open(driver, dsn string) (*DB, error) {
if dsn == "" {
return nil, errors.New("empty dsn")
}
return &DB{dsn: dsn}, nil
}
func (db *DB) Ping() error { return nil }
func (db *DB) Close() error { return nil }
func main() {
db, err := Open("postgres", "postgres://localhost/mydb")
if err != nil {
fmt.Println("open error:", err)
return
}
defer db.Close()
if err := db.Ping(); err != nil {
fmt.Println("ping error:", err)
return
}
fmt.Println("connected to", db.dsn)
}Context-Aware Variants
Prefer PingContext, QueryContext, and ExecContext so calls respect deadlines and cancellation. Passing a context bounds how long a hung database call can block.
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
err := db.PingContext(ctx)The DSN Format
Each driver defines its own DSN. PostgreSQL accepts a URL, MySQL uses user:pass@tcp(host:3306)/dbname. Always check the drivers docs and avoid hardcoding credentials.
One Pool, Long Lived
A common mistake is calling sql.Open per request. That defeats pooling and exhausts connections. Open once at startup, store the *sql.DB, and reuse it everywhere.
Quick Check
Test your connection knowledge.
Recap
You learned opening a connection:
- Blank-import a driver, call sql.Open with driver and DSN
- *sql.DB is a concurrency-safe pool, opened once
- Ping verifies real connectivity
- Tune the pool and use context-aware methods
- defer db.Close() at shutdown
Frequently asked questions
Is the “Opening a Connection” lesson free?
Yes — the full text of “Opening a Connection” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Opening a Connection”?
Connect to a database. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Opening a Connection” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Opening a Connection
- Querying Rows
- Prepared Statements
- Transactions