线上回滚笔记-02

DSN(Data source name) 初探

​ 最近的服务需要到MySql中进行增删查改,数据库一直是自己的弱项,碰巧这个机会,好好补补这方面的知识点。第一步,链接数据库的地址,ip地址、端口、账号、密码和数据库名都给你了,怎么去组织这些字段,当然google都会有答案,更好的方式是彻底的理解。

​ 维基百科(https://en.wikipedia.org/wiki/Data_source_name),给出的答案是:In computing, a data source name is a string that has an associated data structure used to describe a connection to a data source. 并且主要用于开放数据库的连接和Java数据库的连接。从用途和语言的角度,DSN的形式千变万化,但是主要作用都是对数据源进行连接,数据源可以是文件、数据库、系统和用户等。也可以在任意的语言形式中使用。

The Data Source Name has a common format, like e.g. PEAR DB uses it, but without type-prefix (optional parts marked by squared brackets):

1
[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]

A DSN in its fullest form:

1
username:password@protocol(address)/dbname?param=value

Except for the databasename, all values are optional.

常用实例:

1
2
3
4
user@unix(/path/to/socket)/dbname?charset=utf8
user:password@tcp(localhost:5555)/dbname?charset=utf8
user:password@/dbname
user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname

Ref: https://github.com/go-sql-driver/mysql

使用MySQL数据库

go中使用mysql的基本方式, 包括增删查改。使用模式基本为:

  1. stmt, err := db.Prepare() 建立基本连接
  2. res, err := stmt.Exec() 执行基本操作,输入参数填入第一步sql语句的洞中
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
package main

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

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

func main() {
db, err := sql.Open("mysql", "astaxie:astaxie@/test?charset=utf8")
checkErr(err)

//插入数据
stmt, err := db.Prepare("INSERT userinfo SET username=?,department=?,created=?")
checkErr(err)

res, err := stmt.Exec("astaxie", "研发部门", "2012-12-09")
checkErr(err)

id, err := res.LastInsertId()
checkErr(err)

fmt.Println(id)
//更新数据
stmt, err = db.Prepare("update userinfo set username=? where uid=?")
checkErr(err)

res, err = stmt.Exec("astaxieupdate", id)
checkErr(err)

affect, err := res.RowsAffected()
checkErr(err)

fmt.Println(affect)

//查询数据
rows, err := db.Query("SELECT * FROM userinfo")
checkErr(err)

for rows.Next() {
var uid int
var username string
var department string
var created string
err = rows.Scan(&uid, &username, &department, &created)
checkErr(err)
fmt.Println(uid)
fmt.Println(username)
fmt.Println(department)
fmt.Println(created)
}

//删除数据
stmt, err = db.Prepare("delete from userinfo where uid=?")
checkErr(err)

res, err = stmt.Exec(id)
checkErr(err)

affect, err = res.RowsAffected()
checkErr(err)

fmt.Println(affect)

db.Close()

}

func checkErr(err error) {
if err != nil {
panic(err)
}
}