Connect to mysql from golang

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
package main

import (
"database/sql"
"fmt"
"runtime"
_ "github.com/go-sql-driver/mysql"
"time"
)

type DBStruct struct {
db *sql.DB
}

var dbString string

func (dbs *DBStruct) dbOpen() (err error) {
dbs.db, err = sql.Open("mysql", dbString)
if err != nil {
fmt.Println("ERROR dbOpen")
}
return err
}

func (dbs *DBStruct) dbClose() (err error) {
err = dbs.db.Ping()
if err != nil {
fmt.Println(err)
return err
}
defer dbs.db.Close()
return err
}

func (dbs *DBStruct) dbCreate(tableName string) (err error) {
err = nil
err = dbs.db.Ping()
if err != nil {
fmt.Println(err)
return err
}
c0 := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s", tableName)
c1 := fmt.Sprintf("%s ( id INT AUTO_INCREMENT PRIMARY KEY, ", c0)
c2 := fmt.Sprintf("%s LastUptTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP) ", c1)
if _, err = dbs.db.Exec(c2); err != nil {
fmt.Println(err)
return err
}
return err
}

func (dbs *DBStruct) dbInsert(tableName string) (err error) {
err = dbs.db.Ping()
if err != nil {
fmt.Println(err)
return err
}
t := time.Now()
var INSERT string
INSERT = fmt.Sprintf("INSERT INTO %s (LastUptTime) VALUES( '%s') ", tableName, t.Format("20060102150405"))
if _, err = dbs.db.Exec(INSERT); err != nil {
fmt.Println(err)
return err
}
return err
}

func main() {
ip := "10.62.8.175:3306"
dbName := "test"
dbString = "root:123456@tcp(" + ip + ")/" + dbName
tableName := "jeff"
runtime.GOMAXPROCS(runtime.NumCPU())
var dbs DBStruct
dbs.dbOpen()
dbs.dbCreate(tableName)
dbs.dbInsert(tableName)
dbs.dbClose()
}