-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
36 lines (31 loc) · 1.07 KB
/
db.go
File metadata and controls
36 lines (31 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main
import (
"database/sql"
)
func createTable(db *sql.DB) sql.Result {
query := "create table if not exists books (id serial, title varchar, author varchar, year varchar);"
result, err := db.Exec(query)
logFatal(err) // implemented in main.go
return result
}
func insertData(db *sql.DB) bool {
query := `
insert into books (title, author, year) values ('Golang is great', 'Mr. Great', '2012');
insert into books (title, author, year) values ('Golang is magnific', 'Mr. Magnific', '2013');
insert into books (title, author, year) values ('Os sertões', 'Euclides da Cunha', '1895');
insert into books (title, author, year) values ('Memórias póstumas de Bráz Cubas', 'Machado de Assis', '1878');
insert into books (title, author, year) values ('O ultimo dos justos', 'Andre Schwart-Bart', '1960');
`
rows, _ := db.Query("select count(*) from books;")
defer rows.Close()
var count int
// count the number of rows
for rows.Next() {
rows.Scan(&count)
}
if count == 0 {
_, err := db.Exec(query)
logFatal(err) // implemented in main.go
}
return true
}