1. 程式人生 > >親測可用的golang sql例程與包管理

親測可用的golang sql例程與包管理

!= int panic 創建表 exec println ngs 管理 from

sqlite與golang

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、包管理,apt-get install golang-glide 然後glide init,會自動產生glide.yaml,註意需要配置環境變量GOPATH,GOPATH可以是任意目錄,但是init的時候會提示沒有src目錄,所以需要在GOPATH下面mkdir src文件夾。

2、glide get xxxx,然後將$GOPATH裏面的包,cp到GOPATH的指定目錄

親測可用的golang sql例程與包管理