数据库
首页 > 数据库> > Go语言操作sqllite

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())
	}
}

 

标签:CheckError,语言,err,res,fmt,db,util,Go,sqllite
来源: https://blog.csdn.net/qq_29777207/article/details/89673160