Drivers
A SQL driver is a package that registers itself with database/sql so sql.Open(name, dsn) can dial a database. You import the driver for side effects: import _ "github.com/jackc/pgx/v5/stdlib".
Detailed Explanation
database/sql has no Postgres or MySQL code. Drivers implement driver.Driver and call sql.Register("pgx", ...). Your application imports the driver with a blank identifier so init runs. The first argument to sql.Open must match the registered name ("pgx", "mysql", "sqlite3").
Blank import is required if you only use database/sql. Forgetting it produces sql: unknown driver. The import must be in a package that is actually linked — a test-only import will not help the server binary.
Native vs database/sql adapters. jackc/pgx can be used as a native pool (pgxpool) without database/sql, or as a driver via pgx/stdlib. Native APIs expose listen/notify and pipeline mode. database/sql is portable across databases. Pick one per service; wrapping both is rare.
DSNs are driver-specific. Postgres URLs, MySQL user:pass@tcp(host:3306)/db, SQLite file paths. Parse errors often show up on first Ping, not on Open.
What it costs. A driver is a dependency you pin in go.mod. Keep one driver per database. Loading two MySQL drivers under different names is possible and confusing. In tests, prefer a real engine or a fake repository — a mock driver is almost never worth it.
Code Examples
package main
import (
"database/sql"
_ "github.com/jackc/pgx/v5/stdlib"
)
func open() (*sql.DB, error) {
return sql.Open("pgx", "postgres://localhost:5432/shop")
}
func main() {}The blank import exists for init registration.
// The blank import exists for init registration.
import _ "github.com/go-sql-driver/mysql"Common Gotchas
`pgx` native and `pgx/stdlib` are different APIs
`sql.Open("pgx", ...)` needs the stdlib adapter.
SQLite drivers often use cgo
check the module you picked (`modernc.org/sqlite` is cgo-free).
Two packages registering the same name panic at init
Two packages registering the same name panic at init