-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
115 lines (76 loc) · 2.25 KB
/
main.go
File metadata and controls
115 lines (76 loc) · 2.25 KB
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
109
110
111
112
113
114
115
package main
import (
"database/sql"
"fmt"
dbConfig "./dbconfig"
_ "github.com/lib/pq"
)
var db *sql.DB
var err error
func main() {
fmt.Printf("Accessing %s ... ", dbConfig.DbName)
db, err = sql.Open(dbConfig.PostgresDriver, dbConfig.DataSourceName)
if err != nil {
panic(err.Error())
} else {
fmt.Println("Connected!")
}
defer db.Close()
sqlSelect()
//sqlSelectID()
//sqlInsert()
//sqlUpdate()
//sqlDelete()
}
func sqlSelect() {
sqlStatement, err := db.Query("SELECT id, title, body FROM " + dbConfig.TableName)
checkErr(err)
for sqlStatement.Next() {
var article dbConfig.Article
err = sqlStatement.Scan(&article.ID, &article.Title, &article.Body)
checkErr(err)
fmt.Printf("%d\t%s\t%s \n", article.ID, article.Title, article.Body)
}
}
func sqlSelectID() {
var article dbConfig.Article
sqlStatement := fmt.Sprintf("SELECT id, title, body FROM %s where id = $1", dbConfig.TableName)
err = db.QueryRow(sqlStatement, 1).Scan(&article.ID, &article.Title, &article.Body)
checkErr(err)
fmt.Printf("%d\t%s\t%s \n", article.ID, article.Title, article.Body)
}
func sqlInsert() {
sqlStatement := fmt.Sprintf("INSERT INTO %s VALUES ($1,$2, $3)", dbConfig.TableName)
insert, err := db.Prepare(sqlStatement)
checkErr(err)
result, err := insert.Exec(5, "Maps in Golang", "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium")
checkErr(err)
affect, err := result.RowsAffected()
checkErr(err)
fmt.Println(affect)
}
func sqlUpdate() {
sqlStatement := fmt.Sprintf("update %s set body=$1 where id=$2", dbConfig.TableName)
update, err := db.Prepare(sqlStatement)
checkErr(err)
result, err := update.Exec("But I must explain to you how all this mistaken idea", 5)
checkErr(err)
affect, err := result.RowsAffected()
checkErr(err)
fmt.Println(affect)
}
func sqlDelete() {
sqlStatement := fmt.Sprintf("delete from %s where id=$1", dbConfig.TableName)
delete, err := db.Prepare(sqlStatement)
checkErr(err)
result, err := delete.Exec(5)
checkErr(err)
affect, err := result.RowsAffected()
checkErr(err)
fmt.Println(affect)
}
func checkErr(err error) {
if err != nil {
panic(err.Error())
}
}