-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository_sqllite.go
108 lines (97 loc) · 2.41 KB
/
repository_sqllite.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"log"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
func checkIfTableExist() bool {
var people People
db, err := gorm.Open("sqlite3", "gorm.db")
if err != nil {
log.Fatal("Can not connect to DB. Caused by ", err)
}
exist := db.HasTable(&people)
return exist
}
func createTable() (errcreated error) {
db, err := gorm.Open("sqlite3", "gorm.db")
if err != nil {
log.Fatal("Can not connect to DB. Caused by ", err)
}
var people People
errcreated = db.CreateTable(&people).Error
if errcreated != nil {
log.Println(errcreated)
}
return errcreated
}
func getAll() (persons []People, err error) {
db, err := gorm.Open("sqlite3", "gorm.db")
if err != nil {
log.Fatal("Can not connect to DB. Caused by ", err)
}
log.Println("Connected to DB")
db.Find(&persons)
defer db.Close()
return persons, err
}
func getPersonByID(id int) (person People, err error) {
db, err := gorm.Open("sqlite3", "gorm.db")
if err != nil {
log.Fatal("Can not connect to DB. Caused by ", err)
}
db.Find(&person, "id = ?", id)
defer db.Close()
return person, err
}
func createNewPerson(name string, surname string, age int, hobby string, active int) (id int) {
db, err := gorm.Open("sqlite3", "gorm.db")
if err != nil {
log.Fatal("Can not connect to DB. Caused by ", err)
}
log.Println("Connected to DB")
new_person := &People{
Name: name,
Surname: surname,
Age: age,
Hobby: hobby,
Active: active,
}
err_create := db.Create(new_person).Error
if err_create != nil {
log.Fatal("Can not create new person. Caused by: ", err_create)
}
defer db.Close()
return new_person.ID
}
func updatePersonByID(id int, name string, surname string, age int, hobby string, active int) {
db, err := gorm.Open("sqlite3", "gorm.db")
if err != nil {
log.Fatal("Can not connect to DB. Caused by ", err)
}
var person People
person.ID = id
new_data := &People{
Name: name,
Surname: surname,
Age: age,
Hobby: hobby,
Active: active,
}
errupdate := db.Model(&person).Where("id = ?", id).Update(new_data).Error
if errupdate != nil {
log.Println("Can not create new person. Caused by: ", errupdate)
} else {
log.Println("Updated ID: ", id)
}
defer db.Close()
}
func deletePersonByID(id int) {
db, err := gorm.Open("sqlite3", "gorm.db")
if err != nil {
log.Fatal("Can not connect to DB. Caused by ", err)
}
var person People
person.ID = id
db.Delete(&person)
}