一、创建测试表

SQL语句如下:

1CREATE TABLE userinfo(
2   uid INTEGER PRIMARY KEY AUTOINCREMENT,
3   username           TEXT    NOT NULL,
4   departname         TEXT    NOT NULL,
5   created        TEXT
6);

二、golang操作SQLite

具体语句如下:

 1package main
 2import (
 3    "database/sql"
 4    "fmt"
 5    _ "github.com/mattn/go-sqlite3"
 6)
 7func main() {
 8    db, err := sql.Open("sqlite3", "./foo.db")
 9    checkErr(err)
10    //插入数据
11    stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) values(?,?,?)")
12    checkErr(err)
13    res, err := stmt.Exec("361way", "研发部", "2019-03-06")
14    checkErr(err)
15    id, err := res.LastInsertId()
16    checkErr(err)
17    fmt.Println(id)
18    //更新数据
19    stmt, err = db.Prepare("update userinfo set username=? where uid=?")
20    checkErr(err)
21    res, err = stmt.Exec("361wayupdate", id)
22    checkErr(err)
23    affect, err := res.RowsAffected()
24    checkErr(err)
25    fmt.Println(affect)
26    //查询数据
27    rows, err := db.Query("SELECT * FROM userinfo")
28    checkErr(err)
29    for rows.Next() {
30        var uid int
31        var username string
32        var department string
33        var created string
34        err = rows.Scan(&uid, &username, &department, &created)
35        checkErr(err)
36        fmt.Println(uid)
37        fmt.Println(username)
38        fmt.Println(department)
39        fmt.Println(created)
40    }
41    //删除数据
42    stmt, err = db.Prepare("delete from userinfo where uid=?")
43    checkErr(err)
44    res, err = stmt.Exec(id)
45    checkErr(err)
46    affect, err = res.RowsAffected()
47    checkErr(err)
48    fmt.Println(affect)
49    db.Close()
50}
51func checkErr(err error) {
52    if err != nil {
53        panic(err)
54    }
55}