go访问数据库

提前准备的数据表结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
CREATE TABLE `userinfo` (
`uid` INT(10) NOT NULL AUTO_INCREMENT,
`username` VARCHAR ( 64 ) NULL DEFAULT NULL,
`departname` VARCHAR ( 64 ) NULL DEFAULT NULL,
`created` DATE NULL DEFAULT NULL,
PRIMARY KEY ( `uid` )
)


CREATE TABLE `userdetail` (
`uid` INT ( 10 ) NOT NULL DEFAULT 0,
`intro` TEXT NULL,
`profile` TEXT NULL,
PRIMARY KEY ( `uid` )
)

1.go操作MySQL数据库

案例使用的是github.com/go-sql-driver/mysql的MySQL驱动,该驱动完全支持database/sql接口,支持keepalive。

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

import (
"database/sql"
"fmt"
"log"
"time"

// 注册driver
_ "github.com/go-sql-driver/mysql"
)

func main() {
// 连接数据库
db, _ := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8")

// 增
stmt, _ := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
res, _ := stmt.Exec("mebaron", "研发部门", time.Now())

id, _ := res.LastInsertId()
fmt.Printf("id: %v\n", id)

// 删
stmt, _ = db.Prepare("delete from userinfo where uid=?")
res, _ = stmt.Exec(id - 3)
effect, _ := res.RowsAffected()
fmt.Printf("delete effect: %v\n", effect)

// 改
stmt, _ = db.Prepare("update userinfo set username=? where uid=?")
res, _ = stmt.Exec("baron", id)

effect, _ = res.RowsAffected()
fmt.Printf("update effect: %v\n", effect)

// 查
rows, _ := db.Query("select * from userinfo")

for rows.Next() {
var (
uid int
username string
departname string
created string
)
rows.Scan(&uid, &username, &departname, &created)
fmt.Println(uid, username, departname, created)
}

// 事务
tx, _ := db.Begin()
stmt, _ = tx.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
res, _ = stmt.Exec("tx", "测试部门", time.Now())
id, _ = res.LastInsertId()
fmt.Printf("id: %v\n", id)
res, _ = tx.Stmt(stmt).Exec("tx-baron", "测试1部门", time.Now())
id, _ = res.LastInsertId()
fmt.Printf("id: %v\n", id)

stmt, _ = tx.Prepare("INSERT userdetail SET uid=?,intro=?,profile=?")
stmt.Exec(id, "intro text", "profile text")

// 事务必须以对Commit或Rollback的调用结束。调用Commit或Rollback后,一旦出现某部分失败,所有对事务的操作都会失败并返回错误值ErrTxDone
tx.Commit()
// tx.Rollback()
}