当前位置:网站首页>Go language sqlx library operation SQLite3 database addition, deletion, modification and query
Go language sqlx library operation SQLite3 database addition, deletion, modification and query
2022-07-02 23:01:00 【xuehu96】
0. quote
sqlx
Than database/sql
It's better to use a little , In fact, almost …
sqlx Address :https://github.com/jmoiron/sqlx
import (
"database/sql"
"fmt"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
1. Connect to database
- 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()
}
Generally, there is no error when connecting to the database , If the file does not exist, it will be created
2. Create data table
SQLite A file is a database , Just create a new data table under the database
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. Additions and deletions
Addition, deletion, modification and MySQL PostgreSQL It's almost the same
Refer to the previous article :https://blog.csdn.net/xuehu96/article/details/124648300
The code hardly needs to be changed
After testing , Place holder with $1, $2, $3 and ?,?,? It's all right
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", " Group ", 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
Delete id by 2 The line of
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() // Number of rows affected by operation
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
hold uid by 3 Of name Change to Zhang San
func testUpdate() error {
sqlu := `UPDATE "main"."user_info" SET "name" = $1 WHERE "uid" = $2`
//sqlu := `UPDATE "main"."user_info" SET "name" = ? WHERE "uid" = ?` // use ? Space occupying is also OK
ret, err := db.Exec(sqlu, " Zhang San ", 3)
if err != nil {
fmt.Printf("update failed, err:%v\n", err)
return err
}
n, err := ret.RowsAffected() // Number of rows affected by operation
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. check
Write a query structure first , Bind directly after finding
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 Doesn't seem to support time.Time
Comments sql.NullString `db:"comments"`
}
4.1 Query single line data
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 Query multiple rows of data
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 function
func main() {
err := InitDB()
if err != nil {
panic(err)
}
defer CloseDB()
err = testSelectAll()
if err != nil {
panic(err)
}
}
边栏推荐
- [leetcode] number of palindromes [9]
- 杰理之充电拔出,无法触摸开机【篇】
- 解决Chrome浏览器和Edeg浏览器主页被篡改的方法
- [LeetCode] 回文数【9】
- kubernetes 使用主机名将 pod 分配在指定节点上
- Higher order operation of bits
- 成功改变splunk 默认URL root path
- Jerry's prototype has no touch, and the reinstallation becomes normal after dismantling [chapter]
- 用sentinel熔断比例阈值改不了,设置慢调用比例没效果
- 海思3559万能平台搭建:在截获的YUV图像上旋转操作
猜你喜欢
MySQL查询附近的数据.并按距离进行排序.
`${}`的用法
[chestnut sugar GIS] how does global mapper batch produce ground contour lines through DSM
损失函数~
海思3559万能平台搭建:在截获的YUV图像上画框
[chestnut sugar GIS] ArcMap - why should the tick of classic capture be removed when using custom capture?
PMP project integration management
Array advanced improvement
Uniapp wechat login returns user name and Avatar
数据分析学习记录--用EXCEL完成简单的单因素方差分析
随机推荐
[chestnut sugar GIS] how does global mapper batch produce ground contour lines through DSM
uniapp微信登录返显用户名和头像
[LeetCode] 多数元素【169】
Kubernetes uses the host name to allocate the pod on the specified node
mysql重置密码,忘记密码,重置root密码,重置mysql密码
傑理之修改不需要長按開機功能【篇】
[LeetCode] 反转字符串【344】
Gas station [problem analysis - > problem conversion - > greed]
位的高阶运算
Lc173. Binary search tree iterator
泛型与反射,看这篇就够了
杰理之、产线装配环节【篇】
The threshold value of fusing proportion cannot be changed with sentinel, and setting the slow call proportion has no effect
Golang面试整理 三 简历如何书写
杰理之样机在多次触摸后会触发关机【篇】
数据分析学习记录(二)---响应曲面法及Design-Expert的简单使用
Jerry's prototype has no touch, and the reinstallation becomes normal after dismantling [chapter]
[leetcode] most elements [169]
Analyse des données dossiers d'apprentissage - - analyse simple de la variance à facteur unique avec Excel
go 4種單例模式