/
main.go
85 lines (84 loc) · 1.85 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
82
83
84
85
package main
import "fmt"
import "database/sql"
import _ "github.com/lib/pq"
type Users struct {
id int
name string
email string
}
func main(){
users := []Users{
{1,"Szabo Daniel","daniel@packt.com"},
{2,"Szabo Florian","florian@packt.com"},
}
db, err := sql.Open("postgres", "user=postgres password=Start!123 host=127.0.0.1 port=5432 dbname=postgres sslmode=disable")
if err != nil {
panic(err)
}else{
fmt.Println("The connection to the DB was successfully initialized!")
}
connectivity := db.Ping()
if connectivity != nil{
panic(connectivity)
}else{
fmt.Println("Good to go!")
}
TableCreate := `
CREATE TABLE users
(
ID integer NOT NULL,
Name text COLLATE pg_catalog."default" NOT NULL,
Email text COLLATE pg_catalog."default" NOT NULL,
CONSTRAINT "Users_pkey" PRIMARY KEY (ID)
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE users
OWNER to postgres;
`
_,err = db.Exec(TableCreate)
if err != nil {
panic(err)
} else{
fmt.Println("The table called Users was successfully created!")
}
insert, insertErr := db.Prepare("INSERT INTO users VALUES($1,$2,$3)")
if insertErr != nil{
panic(insertErr)
}
for _, u := range users{
_, err = insert.Exec(u.id,u.name,u.email)
if err != nil{
panic(err)
}else{
fmt.Println("The user with name:",u.name,"and email:",u.email,"was successfully added!")
}
}
insert.Close()
update, updateErr := db.Prepare("UPDATE users SET Email=$1 WHERE ID=$2")
if updateErr != nil{
panic(updateErr)
}
_, err = update.Exec("user@packt.com",1)
if err != nil{
panic(err)
} else{
fmt.Println("The user's email address was successfully updated!")
}
update.Close()
remove, removeErr := db.Prepare("DELETE FROM users WHERE ID=$1")
if removeErr != nil{
panic(removeErr)
}
_,err = remove.Exec(2)
if err != nil{
panic(err)
}else{
fmt.Println("The second user was successfully removed!")
}
remove.Close()
db.Close()
}