-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
81 lines (72 loc) · 2.16 KB
/
main.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"database/sql"
"log"
"os"
_ "github.com/mattn/go-sqlite3"
)
func main() {
os.Remove("sqlite-database.db")
log.Println("Creating sqlite-database.db...")
file, err := os.Create("sqlite-database.db")
if err != nil {
log.Fatal(err.Error())
}
file.Close()
log.Println("sqlite-database.db created")
sqliteDatabase, _ := sql.Open("sqlite3", "./sqlite-database.db")
defer sqliteDatabase.Close()
createTable(sqliteDatabase)
insertStudent(sqliteDatabase, "0001", "Liana Kim", "Bachelor")
insertStudent(sqliteDatabase, "0002", "Glen Rangel", "Bachelor")
insertStudent(sqliteDatabase, "0003", "Martin Martins", "Master")
insertStudent(sqliteDatabase, "0004", "Alayna Armitage", "PHD")
insertStudent(sqliteDatabase, "0005", "Marni Benson", "Bachelor")
insertStudent(sqliteDatabase, "0006", "Derrick Griffiths", "Master")
insertStudent(sqliteDatabase, "0007", "Leigh Daly", "Bachelor")
insertStudent(sqliteDatabase, "0008", "Marni Benson", "PHD")
insertStudent(sqliteDatabase, "0009", "Klay Correa", "Bachelor")
displayStudents(sqliteDatabase)
}
func createTable(db *sql.DB) {
createStudentTableSQL := `CREATE TABLE student (
"idStudent" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"code" TEXT,
"name" TEXT,
"program" TEXT
);`
log.Println("Create student table...")
statement, err := db.Prepare(createStudentTableSQL)
if err != nil {
log.Fatal(err.Error())
}
statement.Exec()
log.Println("student table created")
}
func insertStudent(db *sql.DB, code string, name string, program string) {
log.Println("Inserting student record ...")
insertStudentSQL := `INSERT INTO student(code, name, program) VALUES (?, ?, ?)`
statement, err := db.Prepare(insertStudentSQL)
if err != nil {
log.Fatalln(err.Error())
}
_, err = statement.Exec(code, name, program)
if err != nil {
log.Fatalln(err.Error())
}
}
func displayStudents(db *sql.DB) {
row, err := db.Query("SELECT * FROM student ORDER BY name")
if err != nil {
log.Fatal(err)
}
defer row.Close()
for row.Next() {
var id int
var code string
var name string
var program string
row.Scan(&id, &code, &name, &program)
log.Println("Student: ", code, " ", name, " ", program)
}
}