-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.go
53 lines (48 loc) · 1.02 KB
/
db.go
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
"log"
)
type Port struct {
Country string `json:"country"`
Port string `json:"port"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
}
// LoadPorts port data from the sqlite database
func LoadPorts() ([]Port, error) {
var ports []Port
// Open the database
db, err := sql.Open("sqlite3", "./dataset/port-list.sqlite")
if err != nil {
return nil, err
}
defer func(db *sql.DB) {
err := db.Close()
if err != nil {
log.Println(err)
}
}(db)
// Query the database
rows, err := db.Query("SELECT country, port, latitude, longitude FROM port_details")
if err != nil {
return nil, err
}
defer func(rows *sql.Rows) {
err := rows.Close()
if err != nil {
log.Println(err)
}
}(rows)
// Iterate through the result set
for rows.Next() {
p := new(Port)
err := rows.Scan(&p.Country, &p.Port, &p.Latitude, &p.Longitude)
if err != nil {
return nil, err
}
ports = append(ports, *p)
}
return ports, nil
}