zoukankan      html  css  js  c++  java
  • Golang之sqlite数据库

    本文章介绍一下golang的sqlite 数据使用,废话少说直接上代码:

    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)
        }
    }
  • 相关阅读:
    关于application/x-www-form-urlencoded编码
    socket 状态
    TCP/IP三次握手详解
    一步步优化JVM四:决定Java堆的大小以及内存占用
    编码问题
    git 应用
    父与子继承
    python try except
    python 编码问题
    requests 库使用方法
  • 原文地址:https://www.cnblogs.com/wanghuixi/p/13253072.html
Copyright © 2011-2022 走看看