CodeBlanks Logo Icon CodeBlanks

The database/sql package

Learn the basics of the database/sql package.

The database/sql package

database/sql offers a common interface for all SQL databases; a driver does the actual talking. The driver is imported with the blank identifier for its side effect and registers itself:

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

The rest of the code is database-independent: moving from MySQL to PostgreSQL usually changes only the driver and the connection string.

sql.DB is a pool

*sql.DB is not a single connection but a connection pool. It is created once at startup and shared by all goroutines; opening and closing it per request is wrong. You tune the pool with SetMaxOpenConns, SetMaxIdleConns and SetConnMaxLifetime.

Practice Registered drivers

sql.Drivers() returns the names of registered drivers. Without importing any driver, print len(sql.Drivers()).

Starter code

main.go
package main

import (
    "database/sql"
    "fmt"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "database/sql"
    "fmt"
)

func main() {
    fmt.Println(len(sql.Drivers()))
}

Expected output

0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is a driver package imported with <code>_</code>?

  • For testing
  • So that it only registers itself in init Correct answer
  • So it compiles faster
  • To keep it secret

Explanation: The driver's init function calls sql.Register; since you don't use the package name in code, the blank identifier is needed.

2 Register the driver

Question
import (
    "database/sql"
    ____ "github.com/lib/pq"
)
Answer
import (
    "database/sql"
    _ "github.com/lib/pq"
)

Explanation: The blank identifier imports the package only for its init side effect.

3 database/sql parts

Term Meaning
database/sql Common interface
Driver Talks to the database
*sql.DB Connection pool
SetMaxOpenConns Pool limit

All lessons in Advanced