So, you’ve built a Go web app, but where do you store all the data? In a database, of course! Whether you’re tracking users, storing orders, or just hoarding cat memes, a database is essential.
Why Use a Database in Go?
Databases let you:
- Store and retrieve data efficiently (No more hardcoded data!)
- Scale your app (So it can handle millions of users… or at least your mom and best friend!)
- Perform complex queries (Finding stuff is easier!)
Go provides excellent support for working with databases through database/sql
and various database drivers.
Choosing a Database
Go supports many databases, including:
- PostgreSQL (Fast, reliable, developer-friendly)
- MySQL (Popular, easy to use, widely supported)
- SQLite (Lightweight, great for small apps)
- MongoDB (NoSQL, perfect for flexible data)
For this guide, we’ll use PostgreSQL as an example.
Installing PostgreSQL Driver
First, install the Go PostgreSQL driver:
go get github.com/lib/pq
Then, import it in your code:
import (
"database/sql"
_ "github.com/lib/pq"
)
Connecting to the Database
Let’s connect our Go app to PostgreSQL.
const dbConnection = "user=postgres password=yourpassword dbname=mydb sslmode=disable"
db, err := sql.Open("postgres", dbConnection)
if err != nil {
log.Fatal(err)
}
defer db.Close()
Now, your app can talk to the database!
Creating a Table
Let’s create a simple users
table.
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name TEXT,
email TEXT UNIQUE
)`)
if err != nil {
log.Fatal(err)
}
Boom! You now have a users
table!
Inserting Data
Let’s add a user.
_, err = db.Exec("INSERT INTO users (name, email) VALUES ($1, $2)", "Alice", "alice@example.com")
if err != nil {
log.Fatal(err)
}
Now Alice is in the database!
Querying Data
Want to get users? Here’s how:
rows, err := db.Query("SELECT id, name, email FROM users")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var id int
var name, email string
rows.Scan(&id, &name, &email)
fmt.Println(id, name, email)
}
Now your app can fetch data like a pro!
Databases make your Go app more powerful, scalable, and useful. Now go build something awesome and store all the data!
0 Comments