Add lesson 5: Talking to Postgres

Daniel Tanaka 1 year ago
parent 3132492005 commit 50ac502051b82ca519848f1cb5e6bdcfe9072d31
3 changed files with 54 additions and 0 deletions
+19-0lessons/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.
+5-0lessons/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.
+30-0lessons/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+}