-
Notifications
You must be signed in to change notification settings - Fork 25
/
model.go
71 lines (54 loc) · 1.39 KB
/
model.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
// model.go
package main
import (
"fmt"
"database/sql"
)
type user struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func (u *user) getUser(db *sql.DB) error {
statement := fmt.Sprintf("SELECT name, age FROM users WHERE id=%d", u.ID)
return db.QueryRow(statement).Scan(&u.Name, &u.Age)
}
func (u *user) updateUser(db *sql.DB) error {
statement := fmt.Sprintf("UPDATE users SET name='%s', age=%d WHERE id=%d", u.Name, u.Age, u.ID)
_, err := db.Exec(statement)
return err
}
func (u *user) deleteUser(db *sql.DB) error {
statement := fmt.Sprintf("DELETE FROM users WHERE id=%d", u.ID)
_, err := db.Exec(statement)
return err
}
func (u *user) createUser(db *sql.DB) error {
statement := fmt.Sprintf("INSERT INTO users(name, age) VALUES('%s', %d)", u.Name, u.Age)
_, err := db.Exec(statement)
if err != nil {
return err
}
err = db.QueryRow("SELECT LAST_INSERT_ID()").Scan(&u.ID)
if err != nil {
return err
}
return nil
}
func getUsers(db *sql.DB, start, count int) ([]user, error) {
statement := fmt.Sprintf("SELECT id, name, age FROM users LIMIT %d OFFSET %d", count, start)
rows, err := db.Query(statement)
if err != nil {
return nil, err
}
defer rows.Close()
users := []user{}
for rows.Next() {
var u user
if err := rows.Scan(&u.ID, &u.Name, &u.Age); err != nil {
return nil, err
}
users = append(users, u)
}
return users, nil
}