当前位置:网站首页>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)
}
}
边栏推荐
- P7072 [CSP-J2020] 直播获奖
- PMP项目整合管理
- Learning records of data analysis (II) -- simple use of response surface method and design expert
- Mask R-CNN
- [chestnut sugar GIS] ArcMap - why should the tick of classic capture be removed when using custom capture?
- Distributed monitoring system ZABBIX
- Jerry's built-in shutdown current is 1.2ua, and then it can't be turned on by long pressing [chapter]
- 【板栗糖GIS】arcscene—如何做出有高度的高程图
- Jericho's thimble reaction when directly touching the prototype is abnormal [chapter]
- Webrtc audio and video capture and playback examples and mediastream media stream analysis
猜你喜欢

boot actuator - prometheus使用

【板栗糖GIS】arcmap—为什么使用自定义捕捉的时候,经典捕捉的勾要去掉呢?

牛客网:最大子矩阵
![[Solved] Splunk: Cannot get username when all users are selected“](/img/13/1e824c8005701e21fc5b4e73308d53.png)
[Solved] Splunk: Cannot get username when all users are selected“

Xshell configuration xforward forwarding Firefox browser

景联文科技低价策略帮助AI企业降低模型训练成本

Jatpack------LiveData
![[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

解决Chrome浏览器和Edeg浏览器主页被篡改的方法

Baidu AI Cloud - create a face recognition application
随机推荐
小鹏P7出事故,安全气囊未弹出,这正常吗?
[leetcode] most elements [169]
Storage unit conversion
Higher order operation of bits
PMP项目整合管理
Distributed monitoring system ZABBIX
杰理之如何测试按键的误触率【篇】
[LeetCode] 回文数【9】
Jerry's modification does not require long press the boot function [chapter]
[chestnut sugar GIS] ArcMap - how to batch modify the font, color, size, etc. of annotation elements
最小生成树 Minimum Spanning Tree
用sentinel熔断比例阈值改不了,设置慢调用比例没效果
Go multithreaded data search
Qt QProgressBar详解
Comprehensively analyze the logic of the shared purchase business model? How sharing purchase empowers Enterprises
Golang的学习路线
高并发介绍及应对
[chestnut sugar GIS] how does global mapper batch produce ground contour lines through DSM
杰理之、产线装配环节【篇】
Addition, deletion, modification and query of handwritten ORM (object relationship mapping)