码迷,mamicode.com
首页 > 数据库 > 详细

纯golang+sqlite3 CRUD

时间:2020-02-10 13:50:15      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:targe   mat   code   rem   timestamp   print   int   研发   update   

参考:https://blog.csdn.net/wyyyh9458/article/details/83550505https://www.v2ex.com/amp/t/618547

看代码应该是谢大神写的;另,我没有修改 go.mod,类似:

`github.com/mattn/go-sqlite3 v2.0.0+incompatible // indirect` --> `github.com/mattn/go-sqlite3 v1.10.0`

直接在liteide中是可以编译成功的。

代码:

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/mattn/go-sqlite3"
)

func main() {
    fmt.Println("打开数据")
    db, err := sql.Open("sqlite3", "./foo.db")
    checkErr(err)

    fmt.Println("生成数据表")
    sql_table := `
CREATE TABLE IF NOT EXISTS "userinfo" (
   "uid" INTEGER PRIMARY KEY AUTOINCREMENT,
   "username" VARCHAR(64) NULL,
   "departname" VARCHAR(64) NULL,
   "created" TIMESTAMP default (datetime(now, localtime))  
);
CREATE TABLE IF NOT EXISTS "userdeatail" (
   "uid" INT(10) NULL,
   "intro" TEXT NULL,
   "profile" TEXT NULL,
   PRIMARY KEY (uid)
);
   `
    db.Exec(sql_table)

    //插入数据
    fmt.Print("插入数据, ID=")
    stmt, err := db.Prepare("INSERT INTO userinfo(username, departname)  values(?, ?)")
    checkErr(err)
    res, err := stmt.Exec("astaxie", "研发部门")
    checkErr(err)
    id, err := res.LastInsertId()
    checkErr(err)
    fmt.Println(id)

    //更新数据
    fmt.Print("更新数据 ")
    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)

    //查询数据
    fmt.Println("查询数据")
    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, username, department, created)
    }

    //删除数据
    fmt.Println("删除数据")
    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)
    }
}

注意sqlite3共享锁的问题:参考https://blog.csdn.net/LOVETEDA/article/details/82690498   golang操作sqlite时database is locked 的坑以及rows.Close()      

纯golang+sqlite3 CRUD

标签:targe   mat   code   rem   timestamp   print   int   研发   update   

原文地址:https://www.cnblogs.com/pu369/p/12290347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!