安裝問題
在import sqlite的時候,golang build 出現(xiàn)以下錯誤钳垮,
exec: "gcc": executable file not found in %PATH%
原因是sqlitle3是個cgo庫沪悲,需要gcd編譯c代碼
然后下載安裝tdm-gcc即可(windosw版本)下載地址:http://tdm-gcc.tdragon.net/download
在golang中使用sqlite3
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "./foo.db")
checkErr(err)
//插入數(shù)據(jù)
stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) values(?,?,?)")
checkErr(err)
res, err := stmt.Exec("astaxie", "研發(fā)部門", "2012-12-09")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Println(id)
//更新數(shù)據(jù)
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)
//查詢數(shù)據(jù)
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)
? ? fmt.Println(username)
? ? fmt.Println(department)
? ? fmt.Println(created)
}
//刪除數(shù)據(jù)
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)
}
}