Connect GORM to MySQL, PostgreSQL, SQLite, and SQL Server. Configure DSNs, connection pool settings, and initialization options.
GORM uses a dialector to abstract database-specific behavior. Install the driver package for your database, then pass the dialector to gorm.Open along with a *gorm.Config.
The returned *gorm.DB is safe for concurrent use. Create it once at application startup and share it across your codebase — do not open a new connection per request.
Connect using a file path or an in-memory database:
import ( "gorm.io/driver/sqlite" "gorm.io/gorm")// File-based databasedb, err := gorm.Open(sqlite.Open("app.db"), &gorm.Config{})if err != nil { panic("failed to open SQLite database")}// In-memory database (data is lost when the process exits)db, err = gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
SQLite allows only one writer at a time. For concurrent write-heavy workloads, use PostgreSQL or MySQL. SQLite is well-suited for local development, CLI tools, and read-heavy embedded applications.
The gorm.io/driver/sqlite package uses CGO to link against the system SQLite library. If you need a pure Go build without CGO, use gorm.io/driver/sqlite (a CGO-free SQLite driver built on modernc.org/sqlite).
gorm.Open wraps the standard library’s database/sql connection pool. You can access the underlying *sql.DB via db.DB() to configure pool behavior:
import "time"sqlDB, err := db.DB()if err != nil { panic(err)}// Maximum number of connections that can be open simultaneouslysqlDB.SetMaxOpenConns(25)// Maximum number of idle connections kept in the poolsqlDB.SetMaxIdleConns(10)// Maximum time a connection can be reused before being closedsqlDB.SetConnMaxLifetime(time.Hour)// Maximum time a connection can sit idle before being closedsqlDB.SetConnMaxIdleTime(30 * time.Minute)
Recommended starting values
Setting
Development
Production
MaxOpenConns
5
25–100
MaxIdleConns
2
10–25
ConnMaxLifetime
1h
1h
ConnMaxIdleTime
5m
30m
Set MaxOpenConns to a value your database can handle. Most managed PostgreSQL instances default to 100 total connections — leave headroom for monitoring, migrations, and admin tools.
Pass a *gorm.Config as the second argument to gorm.Open to control GORM’s behavior at initialization time.
db, err := gorm.Open(dialector, &gorm.Config{ // Skip the automatic ping on open (useful when the DB may not be available at startup) DisableAutomaticPing: true, // Cache prepared statements for reuse across queries PrepareStmt: true, // Skip wrapping single create/update/delete in a transaction (improves throughput) SkipDefaultTransaction: true, // Do not create foreign key constraints when running AutoMigrate DisableForeignKeyConstraintWhenMigrating: true,})
Config fields relevant to connection
Field
Type
Description
DisableAutomaticPing
bool
Skip the ping that verifies the connection on Open. Useful for lazy-connect patterns.
PrepareStmt
bool
Execute all queries as prepared statements and cache them. Reduces parse overhead for repeated queries.
PrepareStmtMaxSize
int
Maximum number of cached prepared statements (LRU eviction). Defaults to math.MaxInt64.
PrepareStmtTTL
time.Duration
TTL for cached prepared statements. Defaults to 1 hour.
SkipDefaultTransaction
bool
Skip the implicit transaction around single create/update/delete operations.
DisableForeignKeyConstraintWhenMigrating
bool
Do not emit CONSTRAINT clauses during AutoMigrate. Useful for databases with limited FK support.
NamingStrategy
schema.Namer
Override the default table/column naming convention.
Logger
logger.Interface
Set a custom logger. Defaults to logger.Default which prints to stdout.
NowFunc
func() time.Time
Override the function used to generate current timestamps.
DryRun
bool
Build SQL statements but do not execute them. Useful for inspecting generated queries.
CreateBatchSize
int
Default batch size when CreateInBatches is called.
TranslateError
bool
Translate database-specific errors into GORM errors (e.g. ErrDuplicatedKey).
If you manage the *sql.DB yourself (for example, to share a connection pool across multiple ORMs or to apply custom TLS configuration), pass it to the dialector directly: