Go语言操作sqllite

package main

import (
	"database/sql"
	"fmt"
	"video/util"
	_ "github.com/mattn/go-sqlite3"
)

func main() {

	db, err := sql.Open("sqlite3","D:/workstation/sqlite/foo.db")
	util.CheckError(err)

	//插入数据
	stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) values(?, ?, ?);")
	util.CheckError(err)
	res, err := stmt.Exec("安琪拉", "人事部门", "2012-12-09")
	util.CheckError(err)
	//返回当前最大id,也就是本次插入所产生的ID
	id, err := res.LastInsertId()
	util.CheckError(err)
	fmt.Println(id)

	//更新数据
	stmt,err = db.Prepare("update userinfo set username=? where uid=?;")
	util.CheckError(err)
	res,err = stmt.Exec("李慕白",id)
	util.CheckError(err)
	affect,err := res.RowsAffected()
	fmt.Println("更新行数:" + string(affect))

	//查询数据
	rows,err := db.Query("SELECT * FROM userinfo")
	util.CheckError(err)

	for rows.Next() {
		var uid int
		var username string
		var department string
		var created string
		err = rows.Scan(&uid, &username, &department, &created)
		util.CheckError(err)
		fmt.Println("uid=" + string(uid),"username=" + username,"department=" + department,"created" + created)
	}

	//删除数据
	stmt,err = db.Prepare("delete from userinfo where uid=?")
	util.CheckError(err)
	res,err = stmt.Exec(id)
	util.CheckError(err)
	affect,err = res.RowsAffected()
	util.CheckError(err)
	fmt.Println("删除:" + string(affect))
	db.Close()

}

package util

import "fmt"

func CheckError(err error) {
	if err != nil {
		fmt.Printf("CheckError, error:%s\n", err.Error())
		panic(err.Error())
	}
}

 

上一篇:C#访问SQLLite数据库效率低下的问题


下一篇:sqllite中实现字符串分割