golang操作sqlite数据库
go-sqlite3开源库地址:https://github.com/mattn/go-sqlite3使用方法代码如下:package mainimport ("database/sql""fmt""log"_ "github.com/mattn/go-sqlite3")const (dbDriverName = "sqlite3"dbName...
·
go-sqlite3
开源库地址:
https://github.com/mattn/go-sqlite3
使用方法代码如下:
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/mattn/go-sqlite3"
)
const (
dbDriverName = "sqlite3"
dbName = "./data.db3"
)
type user struct {
Username string
Age int
Job string
Hobby string
}
func main() {
db, err := sql.Open(dbDriverName, dbName)
if checkErr(err) {
return
}
err = createTable(db)
if checkErr(err) {
return
}
// err = insertData(db, user{"zhangsan", 28, "engineer", "play football"})
// if checkErr(err) {
// return
// }
res, err := queryData(db, "zhangsan")
if checkErr(err) {
return
}
fmt.Println(len(res))
for _, val := range res {
fmt.Println(val)
}
r, err := delByID(db, 1)
if checkErr(err) {
return
}
if r {
fmt.Println("delete row success")
}
}
func createTable(db *sql.DB) error {
sql := `create table if not exists "users" (
"id" integer primary key autoincrement,
"username" text not null,
"age" integer not null,
"job" text,
"hobby" text
)`
_, err := db.Exec(sql)
return err
}
func insertData(db *sql.DB, u user) error {
sql := `insert into users (username, age, job, hobby) values(?,?,?,?)`
stmt, err := db.Prepare(sql)
if err != nil {
return err
}
_, err = stmt.Exec(u.Username, u.Age, u.Job, u.Hobby)
return err
}
func queryData(db *sql.DB, name string) (l []user, e error) {
sql := `select * from users`
stmt, err := db.Prepare(sql)
if err != nil {
return nil, err
}
rows, err := stmt.Query()
if err != nil {
return nil, err
}
var result = make([]user, 0)
for rows.Next() {
var username, job, hobby string
var age, id int
rows.Scan(&id, &username, &age, &job, &hobby)
result = append(result, user{username, age, job, hobby})
}
return result, nil
}
func delByID(db *sql.DB, id int) (bool, error) {
sql := `delete from users where id=?`
stmt, err := db.Prepare(sql)
if err != nil {
return false, err
}
res, err := stmt.Exec(id)
if err != nil {
return false, err
}
_, err = res.RowsAffected()
if err != nil {
return false, err
}
return true, nil
}
func checkErr(e error) bool {
if e != nil {
log.Fatal(e)
return true
}
return false
}
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献3条内容
所有评论(0)