"Life is all about sharing. If we are good at something, pass it on." - Mary Berry

database/sql: never ignore errors

2019-10-16

I’m reading Building RESTful Web Services with Go. And in chapter 4, there is an example to play around with SQLite:

 1db, err := sql.Open("sqlite3", "./books.db")
 2if err != nil {
 3	log.Fatal(err)
 4}
 5
 6statement, err := db.Prepare("CREATE TABLE IF NOT EXISTS books (id INTERGER PRIMARY KEY, isbn INTEGER, author VARCHAR(64), name VARCHAR(64) NULL)")
 7if err != nil {
 8	log.Fatal(err)
 9} else {
10	log.Println("Created table books successfully")
11}
12statement.Exec()
13
14statement, err = db.Prepare("INSERT INTO books (name, author, isbn) VALUES (?, ?, ?)")
15if err != nil {
16	log.Fatal(err)
17}
18statement.Exec("Life is a joke", "The Javna brothers", 123456789)
19log.Println("Inserted first book into db")
20rows, err := db.Query("SELECT id, name, author FROM books")
21var tempBook Book
22for rows.Next() {
23	rows.Scan(&tempBook.id, &tempBook.name, &tempBook.author)
24	log.Printf("ID: %d, Book: %s, Author: %s\n", tempBook.id, tempBook.name, tempBook.author)
25}

Read More...