Welcome to our comprehensive guide on Go (Golang) Database Connections! In this lesson, we'll learn how to connect your Go applications to databases. By the end of this tutorial, you'll be able to establish connections with popular databases like SQLite, MySQL, and PostgreSQL.
Go is a powerful programming language that's gaining popularity due to its simplicity, efficiency, and versatility. When it comes to database connections, Go offers a wide range of packages to handle various database systems.
Before diving into the tutorial, make sure you have:
SQLite is a popular, lightweight, and self-contained database engine. Let's learn how to connect Go to an SQLite database.
First, we need to install the sqlite3 package. Open your terminal and run the following command:
go get github.com/mattn/go-sqlite3Next, let's create a simple SQLite database and table using the sqlite3 command-line tool.
sqlite3 sample.db
SQLite version 3.32.0 2020-01-28 13:49:18
Enter ".help" for usage hints.
sqlite> CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT);
sqlite> .quitNow, let's write Go code to connect to our SQLite database and insert some data.
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "./sample.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
_, err = db.Exec(`INSERT INTO users (name) VALUES (?)`, "John Doe")
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("SELECT name FROM users")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var name string
err = rows.Scan(&name)
if err != nil {
log.Fatal(err)
}
fmt.Println(name)
}
}Save the code as main.go and run it using the following command:
go run main.goYou should see "John Doe" printed in the output.
Connecting to MySQL and PostgreSQL involves using different packages. Here's a brief overview:
go get github.com/go-sql-driver/mysqlgo get github.com/lib/pqYou can find examples for MySQL and PostgreSQL connections in our extended tutorial.
Which Go package do we use for SQLite?