Go Opening Database Connection

beginner
9 min

Go Opening Database Connection

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.

Why Go for Database Connections? 💡

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.

Prerequisites 📝

Before diving into the tutorial, make sure you have:

  1. Installed Go on your system (if not, follow these instructions).
  2. Familiarity with basic Go programming concepts like variables, functions, and packages.

Connecting to SQLite 🎯

SQLite is a popular, lightweight, and self-contained database engine. Let's learn how to connect Go to an SQLite database.

Install SQLite Package 📝

First, we need to install the sqlite3 package. Open your terminal and run the following command:

sh
go get github.com/mattn/go-sqlite3

Create a Sample SQLite Database 🎯

Next, let's create a simple SQLite database and table using the sqlite3 command-line tool.

sh
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> .quit

Write Go Code to Connect and Query the Database 🎯

Now, let's write Go code to connect to our SQLite database and insert some data.

go
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:

sh
go run main.go

You should see "John Doe" printed in the output.

Connecting to MySQL and PostgreSQL 🎯

Connecting to MySQL and PostgreSQL involves using different packages. Here's a brief overview:

  • For MySQL, install the go-sql-driver/mysql package:
sh
go get github.com/go-sql-driver/mysql
  • For PostgreSQL, install the pq package:
sh
go get github.com/lib/pq

You can find examples for MySQL and PostgreSQL connections in our extended tutorial.

Quiz 📝

Quick Quiz
Question 1 of 1

Which Go package do we use for SQLite?