微信PK10平台开发Go实战--go语言操作sqlite数据库

栏目: 数据库 · 发布时间: 6年前

内容简介:生命不止,继续 go go go !!!微信PK10平台开发继续与大家分享,go语言的实战,今天介绍的是如何操作sqlite数据库。何为sqlite3?

生命不止,继续 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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Hit Refresh

Hit Refresh

Satya Nadella、Greg Shaw / HarperBusiness / 2017-9-26 / USD 20.37

Hit Refresh is about individual change, about the transformation happening inside of Microsoft and the technology that will soon impact all of our lives—the arrival of the most exciting and disruptive......一起来看看 《Hit Refresh》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器