Add lesson 5: Talking to Postgres
3 changed files with 54 additions and 0 deletions
lessons/05-talking-to-postgres/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 5: Talking to Postgres | |
| 2 | + | |
| 3 | +Talking to Postgres comes up in almost every real Go project. We start with the why, then write code together. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/go-apis/lessons/5](https://glibcode.net/courses/go-apis/lessons/5) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `main.go`: database/sql with the pgx driver | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +go run ./lessons/05-talking-to-postgres | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## Exercises | |
| 18 | + | |
| 19 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/05-talking-to-postgres/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 5 | |
| 2 | + | |
| 3 | +1. Look up one function or command the example uses in the official documentation. Note one option you didn't know. | |
| 4 | +2. Explain the example to someone who hasn't taken the course. Which part was hardest to explain? | |
| 5 | +3. Make the example ask for its input instead of using a fixed value. | |
lessons/05-talking-to-postgres/main.go ADDED
| @@ -0,0 +1,30 @@ | ||
| 1 | +package main | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "database/sql" | |
| 5 | + "fmt" | |
| 6 | + "log" | |
| 7 | + "os" | |
| 8 | + | |
| 9 | + _ "github.com/jackc/pgx/v5/stdlib" | |
| 10 | +) | |
| 11 | + | |
| 12 | +func main() { | |
| 13 | + db, err := sql.Open("pgx", os.Getenv("DATABASE_URL")) | |
| 14 | + if err != nil { | |
| 15 | + log.Fatal(err) | |
| 16 | + } | |
| 17 | + defer db.Close() | |
| 18 | + | |
| 19 | + rows, err := db.Query("SELECT id, title FROM todos WHERE done = $1", false) | |
| 20 | + if err != nil { | |
| 21 | + log.Fatal(err) | |
| 22 | + } | |
| 23 | + defer rows.Close() | |
| 24 | + for rows.Next() { | |
| 25 | + var id int | |
| 26 | + var title string | |
| 27 | + rows.Scan(&id, &title) | |
| 28 | + fmt.Println(id, title) | |
| 29 | + } | |
| 30 | +} | |