当前位置:网站首页>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)
}
}
边栏推荐
猜你喜欢

odoo13搭建医院HRP环境(详细步骤)

Mask R-CNN
![[NPUCTF2020]ezlogin xPATH注入](/img/6e/dac4dfa0970829775084bada740542.png)
[NPUCTF2020]ezlogin xPATH注入
![Jielizhi, production line assembly link [chapter]](/img/0d/102596ad13aafd9c6133509d9064dd.png)
Jielizhi, production line assembly link [chapter]

数据分析学习记录(二)---响应曲面法及Design-Expert的简单使用

创新实力再获认可!腾讯安全MSS获2022年度云原生安全守护先锋

MySQL reset password, forget password, reset root password, reset MySQL password

世界环境日 | 周大福用心服务推动减碳环保

泛型与反射,看这篇就够了

Dahua cloud native load balancing article - the passenger flow of small restaurants has increased
随机推荐
Gas station [problem analysis - > problem conversion - > greed]
Jerry's charge unplugged, unable to touch the boot [chapter]
[leetcode] reverse the word III in the string [557]
Learning records of data analysis (II) -- simple use of response surface method and design expert
P1007 独木桥
性能优化----严苛模式
世界环境日 | 周大福用心服务推动减碳环保
Lambda expression: an article takes you through
Storage unit conversion
Rails 3 activerecord: sort by association count - rails 3 activerecord: order by count on Association
【硬件】标准阻值的由来
送给即将工作的自己
Comprehensively analyze the logic of the shared purchase business model? How sharing purchase empowers Enterprises
数据分析学习记录--用EXCEL完成简单的单因素方差分析
Jerry's fast touch does not respond [chapter]
LC173. 二叉搜索树迭代器
数组进阶提高
高并发介绍及应对
创新实力再获认可!腾讯安全MSS获2022年度云原生安全守护先锋
easyclick,ec权朗网络验证源码