-
Notifications
You must be signed in to change notification settings - Fork 14
/
sql.go
executable file
·64 lines (56 loc) · 1.25 KB
/
sql.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
package main
import (
"fmt"
"strings"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
var (
dbConn *sql.DB
)
func SQLConnect(sqlserver string, sqluser string, sqlpass string, sqldb string) (err error) {
if strings.ContainsRune(sqlserver, ':') {
dbConn, err = sql.Open("mysql", sqluser+":"+sqlpass+"@tcp("+sqlserver+")/"+sqldb)
} else {
dbConn, err = sql.Open("mysql", sqluser+":"+sqlpass+"@tcp("+sqlserver+":3306)/"+sqldb)
}
if err == nil {
err = dbConn.Ping()
}
return
}
type PhonebookEntry struct {
Name string
Extension string
}
func SQLSearch(sqlQuery string, sqlVals []interface{}) ([]*PhonebookEntry, error) {
var (
rows *sql.Rows
err error
result []*PhonebookEntry = []*PhonebookEntry{}
)
rows, err = dbConn.Query(sqlQuery, sqlVals...)
if err != nil {
return nil, fmt.Errorf("Database Error: %s", err)
}
defer rows.Close()
for rows.Next() {
var (
name string
extension string
)
err := rows.Scan(&name, &extension)
if err != nil {
return nil, fmt.Errorf("Database Error: %s", err)
}
result = append(result, &PhonebookEntry{
Name: name,
Extension: extension,
})
}
err = rows.Err()
if err != nil {
return nil, fmt.Errorf("Database Error: %s", err)
}
return result, nil
}