当前位置:网站首页>Go语言sqlx库操作SQLite3数据库增删改查
Go语言sqlx库操作SQLite3数据库增删改查
2022-07-02 22:09:00 【xuehu96】
0. 引用
sqlx比database/sql要好用一点点,其实差不多的…
sqlx地址:https://github.com/jmoiron/sqlx
import (
"database/sql"
"fmt"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
1. 连接数据库
- sql.Open
- sql.Close
var db *sql.DB
func InitDB() (err error) {
dsn := "./data.db"
db, err = sql.Open("sqlite3",dsn)
if err != nil {
fmt.Printf("connect DB failed, err:%v\n", err)
return
}
return
}
func Close() {
db.Close()
}
连接数据库一般是不会报错的,文件不存在则会创建
2. 创建数据表
SQLite一个文件就是一个数据库,在数据库下新建数据表就可以了
func testCreateTable() error {
sqlc := ` CREATE TABLE "user_info" ( "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "uid" INTEGER(8) NOT NULL, "name" text(255) NOT NULL, "group" TEXT(255) NOT NULL, "balance" integer(8) NOT NULL, "proportion" real(8) NOT NULL, "create_time" integer(4) NOT NULL, "comments" TEXT(255) ); CREATE INDEX "indexs" ON "user_info" ( "name", "group" ); CREATE UNIQUE INDEX "uniques" ON "user_info" ( "uid" ); `
_, err := db.Exec(sqlc)
if err != nil {
return err
}
return nil
}
3. 增删改
增删改和MySQL PostgreSQL的操作差不多
参考之前的文章:https://blog.csdn.net/xuehu96/article/details/124648300
代码几乎都不用改
经过测试,占位符用$1, $2, $3和 ?,?,?都是可以的
3.1 insert
func testInsert() error {
sqli := `INSERT INTO "main"."user_info" ("uid", "name", "group", "balance", "proportion", "create_time", "comments") VALUES ($1, $2, $3, $4, $5, $6, $7);`
_, err := db.Exec(sqli, 100, "xuehu96", "组", 2.33, 27.148, "2022-06-27 18:11:22", nil)
if err != nil {
return err
}
fmt.Printf("insert success\n")
return nil
}
3.2 delete
删除id为2的行
func testDelete() error {
sqld := `DELETE FROM "main"."user_info" WHERE "id" = $1`
ret, err := db.Exec(sqld, 2)
if err != nil {
fmt.Printf("delete failed, err:%v\n", err)
return err
}
n, err := ret.RowsAffected() // 操作影响的行数
if err != nil {
fmt.Printf("get RowsAffected failed, err:%v\n", err)
return err
}
fmt.Printf("delete success, affected rows:%d\n", n)
return nil
}
3.3 update
把uid为3的name改为张三
func testUpdate() error {
sqlu := `UPDATE "main"."user_info" SET "name" = $1 WHERE "uid" = $2`
//sqlu := `UPDATE "main"."user_info" SET "name" = ? WHERE "uid" = ?` // 用?占位也行
ret, err := db.Exec(sqlu, "张三", 3)
if err != nil {
fmt.Printf("update failed, err:%v\n", err)
return err
}
n, err := ret.RowsAffected() // 操作影响的行数
if err != nil {
fmt.Printf("get RowsAffected failed, err:%v\n", err)
return err
}
fmt.Printf("update success, affected rows:%d\n", n)
return nil
}
4. 查
查询前先写一个结构体,查到后直接绑定
type UserInfoType struct {
Id int `db:"id"`
Uid int64 `db:"uid"`
Name string `db:"name"`
Group string `db:"group"`
Balance float64 `db:"balance"`
Proportion float64 `db:"proportion"`
CreateTime string `db:"create_time"` // SQLite似乎不支持time.Time
Comments sql.NullString `db:"comments"`
}
4.1 查询单行数据
func testSelectOne() error {
sqls := `SELECT * FROM "main"."user_info" WHERE "uid" = $1`
var user UserInfoType
err := db.Get(&user, sqls, 3)
if err != nil {
fmt.Printf("get failed, err:%v\n", err)
return err
}
fmt.Printf("one user: %#v\n", user)
return nil
}
4.2 查询多行数据
func testSelectAll() error {
sqls := `SELECT * FROM "main"."user_info" WHERE "uid" > $1`
var users []UserInfoType
err := db.Select(&users, sqls, 0)
if err != nil {
fmt.Printf("query failed, err:%v\n", err)
return err
}
fmt.Printf("all users: %#v\n", users)
return nil
}

5. main函数
func main() {
err := InitDB()
if err != nil {
panic(err)
}
defer CloseDB()
err = testSelectAll()
if err != nil {
panic(err)
}
}
边栏推荐
- Commodity information management system (C language document version)
- Qt QSplitter拆分器
- Developers share | HLS and skillfully use Axi_ Customize the master bus interface instructions and improve the data bandwidth - area exchange speed
- Jielizhi, production line assembly link [chapter]
- [autosar-dcm] - 4.3-how UDS $22 and $2e services read and write NVM data
- Leetcode circular linked list (fast and slow pointer) code line by line interpretation
- Mathematical modeling -- graph and network models and methods (I)
- [ODX studio edit PDX] -0.1- how to quickly view the differences in supported diagnostic information between variant variants (service, sub function...)
- [LeetCode] 存在重复元素【217】
- Local dealers play the community group purchase mode and share millions of operations
猜你喜欢

【硬件】标准阻值的由来

Addition, deletion, modification and query of handwritten ORM (object relationship mapping)

数学建模——图与网络模型及方法(一)

性能优化----严苛模式

mysql重置密码,忘记密码,重置root密码,重置mysql密码

Source code analysis - lightweight asynchronous crawler framework Ruia

Uniapp wechat login returns user name and Avatar

【板栗糖GIS】arcmap—如何批量修改注记要素的字体,颜色,大小等
![[chestnut sugar GIS] ArcMap - how to batch modify the font, color, size, etc. of annotation elements](/img/b1/1fae909fb6a9231096a93d741d6426.png)
[chestnut sugar GIS] ArcMap - how to batch modify the font, color, size, etc. of annotation elements

Comprehensively analyze the logic of the shared purchase business model? How sharing purchase empowers Enterprises
随机推荐
Leetcode circular linked list (fast and slow pointer) code line by line interpretation
World Environment Day | Chow Tai Fook serves wholeheartedly to promote carbon reduction and environmental protection
大话云原生之负载均衡篇-小饭馆客流量变大了
杰理之内置短按再长按,不管长按多长时间都是短按【篇】
杰理之样机在多次触摸后会触发关机【篇】
杰理之样机无触摸,拆机之后重新安装变正常【篇】
杰理之修改不需要长按开机功能【篇】
PHP optimizes SQL queries in foreach
【板栗糖GIS】arcmap—为什么使用自定义捕捉的时候,经典捕捉的勾要去掉呢?
Introduction and response to high concurrency
Il n'est pas nécessaire d'appuyer longtemps sur la fonction de démarrage pour modifier Jelly [chapitre]
Golang面试整理 三 简历如何书写
Share 10 JS closure interview questions (diagrams), come in and see how many you can answer correctly
Golang的学习路线
P7072 [CSP-J2020] 直播获奖
`Usage of ${}`
杰理之如何测试按键的误触率【篇】
Qt QSplitter拆分器
首批 | 腾讯云完成国内首个云原生安全成熟度评估
go 条件变量