Databases with database/sql

Contents
sql.Open is lazy
Query rows
Exec writes
Tune the pool

sql.Open is lazy

The database/sql package talks to databases through drivers. The program imports the driver for its side effects only, while all real calls go through the generic DB handle.

sql.Open only validates the arguments and returns a handle, so it never touches the network. Call Ping right after Open when the program must fail fast on a wrong address or bad credentials.

The driver import below is a placeholder. Swap example.com/driver with the driver package for the database in use and keep the blank identifier in front of it.

package main import ( "database/sql" "fmt" _ "example.com/driver" ) func main() { db, err := sql.Open("somedb", "user:pass@/dbname") if err != nil { fmt.Println(err) return } if err := db.Ping(); err != nil { fmt.Println(err) return } fmt.Println("ready") db.Close() }

ready

Query rows

Query runs a statement that returns rows and hands back a Rows cursor. The program walks the cursor with Next and copies every row into variables with Scan.

Three cleanups keep reads safe: defer Close on the cursor, check Scan errors inside the loop, and check Err after the loop for failures that surface while streaming.

package main import ( "database/sql" "fmt" _ "example.com/driver" ) func main() { db, err := sql.Open("somedb", "user:pass@/dbname") if err != nil { fmt.Println(err) return } rows, err := db.Query("SELECT id, name FROM users") if err != nil { fmt.Println(err) return } defer rows.Close() for rows.Next() { var id int var name string if err := rows.Scan(&id, &name); err != nil { fmt.Println(err) return } fmt.Println(id, name) } if err := rows.Err(); err != nil { fmt.Println(err) } }

1 Ann

2 Bob

Exec writes

Exec runs a statement that returns no rows, such as insert, update, or delete. Arguments travel separately from the text, so question marks in the statement fill with safe values and injection has no room to grow.

The returned Result reports what changed. LastInsertId gives the new key on databases that support it, and RowsAffected tells how many rows the statement touched.

package main import ( "database/sql" "fmt" _ "example.com/driver" ) func main() { db, err := sql.Open("somedb", "user:pass@/dbname") if err != nil { fmt.Println(err) return } res, err := db.Exec("INSERT INTO users(name) VALUES(?)", "Ann") if err != nil { fmt.Println(err) return } id, _ := res.LastInsertId() rows, _ := res.RowsAffected() fmt.Println(id, rows) }

3 1

Tune the pool

A DB handle owns a pool of connections that opens and closes links behind the scenes. Defaults work for experiments, but services should set explicit limits before traffic arrives.

SetMaxOpenConns caps parallel links, SetMaxIdleConns keeps warm links ready for reuse, and SetConnMaxLifetime retires old links so load balancers and restarts stay smooth.

package main import ( "database/sql" "fmt" "time" _ "example.com/driver" ) func main() { db, err := sql.Open("somedb", "user:pass@/dbname") if err != nil { fmt.Println(err) return } db.SetMaxOpenConns(10) db.SetMaxIdleConns(5) db.SetConnMaxLifetime(5 * time.Minute) if err := db.Ping(); err != nil { fmt.Println(err) return } fmt.Println("ready") db.Close() }

ready

Next: Benchmarks and profiling

Article author: Arthur Isaev

Related articles
Golang
Go course: zero to hero in 50 lessons
What is Go and where it runs
Install Go and check the version
Your first Go program
Modules with go mod
Variables
Constants
Types
Numbers
Strings
Conditions with if
Switch in Go
Loops with for
Arrays in Go
Slices in Go
Maps in Go
Functions in Go
Errors as values
Pointers in Go
Structs in Go
Methods in Go
Interfaces in Go
Embedding instead of inheritance
Generics in Go
Packages and imports
The go toolchain
Testing with go test
Advanced errors
defer in Go
Strings, bytes and runes
Time in Go
JSON
Files and IO
HTTP servers
HTTP clients
Context
Goroutines
Channels
select and sync
CLI: args, flags, env
Logging
Regular expressions
Sorting
Concurrency patterns
Databases with database/sql
Benchmarks and profiling
Toolchain and CI
Project layout
Capstone: wordfreq CLI
Capstone: JSON API server
Hero roadmap: the whole course on one page
Install Go on Windows 11
Install Go on Ubuntu
Install Go on Rocky Linux
Install Go on macOS
Install Go on FreeBSD
Go in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: