So, you’ve connected your Go app to a database—nice! But now it just sits there, doing nothing. Let’s teach it some manners by implementing CRUD operations: Create, Read, Update, and Delete.
What is CRUD?
CRUD stands for:
- Create – Add new records
- Read – Retrieve records
- Update – Modify existing records
- Delete – Remove records
These are the basic functions of any database-driven app.
Setting Up the Database
Let’s use PostgreSQL as an example. Make sure you’ve installed the driver:
go get github.com/lib/pq
And imported it in your Go code:
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq"
)
Now, let’s connect to the database:
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()
Creating a Table
We need a users
table first:
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name TEXT,
email TEXT UNIQUE
)`)
if err != nil {
log.Fatal(err)
}
Your database is now ready for CRUD operations!
Create (Insert 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)
}
Alice is now stored in the database!
Read (Fetch Data)
Want to get all users?
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 read user data!
Update (Modify Data)
Oops! Alice changed her name to "Alicia." Let’s update her record:
_, err = db.Exec("UPDATE users SET name = $1 WHERE email = $2", "Alicia", "alice@example.com")
if err != nil {
log.Fatal(err)
}
Boom! Alice is now Alicia.
Delete (Remove Data)
Alice—oops, I mean Alicia—decides to delete her account.
_, err = db.Exec("DELETE FROM users WHERE email = $1", "alice@example.com")
if err != nil {
log.Fatal(err)
}
Goodbye, Alice!
Conclusion
CRUD operations are the backbone of any database-driven app. With database/sql
, your Go app can now add, read, update, and delete data like a pro. Now go forth and CRUD something amazing!
0 Comments