生命不止,继续 go go go !!!微信PK10平台开发
继续与大家分享,go语言的实战,今天介绍的是如何操作sqlite数据库。
何为sqlite3?
SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine.
最主要的是,sqlite是一款轻型的数据库
database/sql包
go中有一个database/sql package,我们看看是怎样描述的:
Package sql provides a generic interface around SQL (or SQL-like) databases.
The sql package must be used in conjunction with a database driver
很清晰吧,需要我们自己提供一个database driver。当然,我们可以在github上找到相关的sqlite3的driver,稍后介绍。
下面介绍接个数据相关的操作:
Open
func Open(driverName, dataSourceName string) (*DB, error)
1
需要提供两个参数,一个driverName,一个数据库的名。
Prepare
func (db DB) Prepare(query string) (Stmt, error)
1
Prepare creates a prepared statement for later queries or executions.
返回的 *Stmt是什么鬼?
Stmt
Stmt is a prepared statement. A Stmt is safe for concurrent use by multiple goroutines.
func (*Stmt) Exec
准备完成后,就要执行了。
func (s *Stmt) Exec(args ...interface{}) (Result, error)
1
Exec executes a prepared statement with the given arguments and returns a Result summarizing the effect of the statement.
返回的Resault是什么鬼?
Result
type Result interface {
// LastInsertId returns the integer generated by the database
// in response to a command. Typically this will be from an
// "auto increment" column when inserting a new row. Not all
// databases support this feature, and the syntax of such
// statements varies.
LastInsertId() (int64, error)
// RowsAffected returns the number of rows affected by an
// update, insert, or delete. Not every database or database
// driver may support this.
RowsAffected() (int64, error)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
Query
func (s Stmt) Query(args ...interface{}) (Rows, error)
1
查询,返回的Rows是什么鬼?
Rows
Rows is the result of a query. Its cursor starts before the first row of the result set.
func (rs *Rows) Next() bool
1
Next prepares the next result row for reading with the Scan method
func (rs *Rows) Scan(dest ...interface{}) error
1
Scan copies the columns in the current row into the values pointed at by dest.
介绍少不多了,下面介绍一个sqlite3的Driver:
mattn/go-sqlite3
sqlite3 driver for go that using database/sql
github地址:
https://github.com/mattn/go-sqlite3
执行:
go get -u github.com/mattn/go-sqlite3
1
下面要开始我们的实战了!!!!
创建数据库,创建表
//打开数据库,如果不存在,则创建
db, err := sql.Open("sqlite3", "./test.db")
checkErr(err)
//创建表
sql_table := `
CREATE TABLE IF NOT EXISTS userinfo(
uid INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(64) NULL,
departname VARCHAR(64) NULL,
created DATE NULL
);
`
db.Exec(sql_table)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
新建一个数据库叫test.db,并在这个数据库中建一个表,叫做userinfo。
userinfo中包含了四个字段,uid username departname created.
把uid设置为主键,并AUTOINCREMENT,自增。
插入数据
stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) values(?,?,?)")
checkErr(err)
res, err := stmt.Exec("wangshubo", "×××", "2017-04-21")
checkErr(err)
1
2
3
4
5
显示Prepare,然后Exec.
接下来,就不再赘述了,我们需要一个基本的sql知识。
补充:import中_的作用
官方解释:
To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name:
import "lib/math"
1
2
3
当导入一个包时,该包下的文件里所有init()函数都会被执行。
然而,有些时候我们并不需要把整个包都导入进来,仅仅是是希望它执行init()函数而已。这个时候就可以使用 import 引用该包。
最后献上全部代码:
package main
import (
"database/sql"
"fmt"
"time"
_ "github.com/mattn/go-sqlite3"
)
func main() {
//打开数据库,如果不存在,则创建
db, err := sql.Open("sqlite3", "./foo.db")
checkErr(err)
//创建表
sql_table := `
CREATE TABLE IF NOT EXISTS userinfo(
uid INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(64) NULL,
departname VARCHAR(64) NULL,
created DATE NULL
);
`
db.Exec(sql_table)
// insert
stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) values(?,?,?)")
checkErr(err)
res, err := stmt.Exec("wangshubo", "×××", "2017-04-21")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Println(id)
// update
stmt, err = db.Prepare("update userinfo set username=? where uid=?")
checkErr(err)
res, err = stmt.Exec("wangshubo_new", id)
checkErr(err)
affect, err := res.RowsAffected()
checkErr(err)
fmt.Println(affect)
// query
rows, err := db.Query("SELECT * FROM userinfo")
checkErr(err)
var uid int
var username string
var department string
var created time.Time
for rows.Next() {
err = rows.Scan(&uid, &username, &department, &created)
checkErr(err)
fmt.Println(uid)
fmt.Println(username)
fmt.Println(department)
fmt.Println(created)
}
rows.Close()
// delete
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)
}
}
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
原文地址:http://blog.51cto.com/13944797/2165939