How to Work With SQL in Go. Know how to query SQL databases in Go… | by Gleb Sakhnov | Feb, 2022

Know how to query SQL databases in Go. The right way

Gleb Sakhnov
Photo by Sunder Muthukumaran on Unsplash

sql.DB

Database driver

import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql",
"user:password@tcp(127.0.0.1:3306)/hello")
if err != nil {
log.Fatal(err)
}
defer db.Close()
}
err = db.Ping()
if err != nil {
// do something here
}

Fetching Data from the Database

How Scan() Works

Single-Row Queries

_, err := db.Exec("DELETE FROM users")  // OK
_, err := db.Query("DELETE FROM users") // BAD

Leave a Comment