22.笔记go语言——使用sqlite驱动
下载驱动
https://github.com/mattn/go-sqlite3
此外,需要在WINDOWS上安装GCC,蛤蟆此处安装的是:tdm64-gcc-5.1.0-2.exe
创建表
sqlite3 foo.db
CREATE TABLE `userinfo` (
`uid` INTEGERPRIMARY KEY AUTOINCREMENT,
`username`VARCHAR(64) NULL,
`departname` VARCHAR(64) NULL,
`created`DATE NULL
);
CREATE TABLE `userdeatail` (
`uid`INT(10) NULL,
`intro`TEXT NULL,
`profile`TEXT NULL,
PRIMARY KEY(`uid`)
);
代码
package main
import (
"database/sql"
"fmt"
_"github.com/mattn/go-sqlite3"
)
func main() {
db,err := sql.Open("sqlite3","foo.db")
checkErr(err)
//插入数据
stmt,err := db.Prepare("INSERT INTO userinfo(username,departname,created) values(?,?,?)")
checkErr(err)
res,err := stmt.Exec("astaxie","研发部门","2012-12-09")
checkErr(err)
id,err := res.LastInsertId()
checkErr(err)
fmt.Println(id)
//更新数据
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)
//查询数据
rows,err := db.Query("SELECT * FROM userinfo")
checkErr(err)
forrows.Next() {
varuid int
varusername string
vardepartment string
varcreated string
err= rows.Scan(&uid,&username,&department,&created)
checkErr(err)
fmt.Println(uid)
fmt.Println(username)
fmt.Println(department)
fmt.Println(created)
}
//删除数据
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) {
iferr != nil {
panic(err)
}
}
PS:之前创建的foo.db需要放到go语言代码所在的目录。
执行结果
1
1
1
astaxieupdate
研发部门
2012-12-09T00:00:00Z
1
与MysqL的一致。