Section 9 of 12
Database Integration
Connect to and interact with databases in Go
Course Progress
Section 9 of 1275% complete
Tutorials
SQL Basics
Go provides database/sql package for working with SQL databases.
Code Examples
Connect to Databasego
package main
import (
"fmt"
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "test.db")
if err != nil {
fmt.Println(err)
}
defer db.Close()
// Create table
sqlStmt := `CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT,
email TEXT
);`
_, err = db.Exec(sqlStmt)
if err != nil {
fmt.Println(err)
}
}CRUD Operationsgo
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, _ := sql.Open("sqlite3", "test.db")
defer db.Close()
// INSERT
stmt, _ := db.Prepare("INSERT INTO users(name, email) VALUES(?, ?)")
stmt.Exec("Alice", "alice@example.com")
// SELECT
rows, _ := db.Query("SELECT id, name, email FROM users")
defer rows.Close()
for rows.Next() {
var id int
var name, email string
rows.Scan(&id, &name, &email)
fmt.Printf("%d: %s (%s)\n", id, name, email)
}
// UPDATE
db.Exec("UPDATE users SET email = ? WHERE name = ?",
"alice.new@example.com", "Alice")
// DELETE
db.Exec("DELETE FROM users WHERE id = ?", 1)
}Exercises
User Database
Create a simple user management database
INTERMEDIATEStarter Code:
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
func main() {
// TODO: Create user database with CRUD operations
}Hands-on Project
Blog Database System
Build a database-backed blog system with posts and comments
ADVANCED
Learning Objectives
- >Database design
- >Relationships
- >Query optimization
Project Tips
- > Start by understanding the requirements
- > Break the project into smaller tasks
- > Test your code frequently as you build
- > Add error handling throughout your code
- > Consider edge cases and validate inputs
- > Document your code with comments