当前位置:网站首页>sqlx库使用
sqlx库使用
2022-07-25 20:52:00 【Johns】
介绍
sqlx是基于Go内置database/sql包上的扩展,主要是简化了sql的使用过程, sqlx的sql.DB, sql.TX, sql.Stmt等保持底层实现不变,因此可以很方便地从database/sql切换到sqlx。sqlx另外还提供了一些功能:
- 可以将Rows内容解析至struct(支持内嵌)、map、slice
- 命名参数支持
- Get/Select可以快速将查询结果转为为struct/slice
安装和连接
go get github.com/jmoiron/sqlximport (
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
func main(){
//连接数据库
// 只用 sqlx.Open() 函数创建连接池,此时只是初始化了连接池,并没有连接数据库.
// 连接都是惰性的,只有调用 sqlx.DB 的方法时,
// 此时才真正用到了连接,连接池才会去创建连接.
DB, err := sqlx.Open("mysql", "root:[email protected]@tcp(127.0.0.1:3306)/test?charset=utf8")
if err != nil {
fmt.Println("connect error:", err)
}
defer DB.Close()
err = DB.Ping()
if err != nil {
fmt.Println("connect ping error:", err)
}
// 连接池配置
DB.SetMaxIdleConns(100)
DB.SetMaxOpenConns(500)
DB.SetConnMaxIdleTime(5*time.Minute)
}表和表实例定义
CREATE TABLE `person` (
`first_name` text,
`last_name` text,
`email` text,
`id` int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4;// Person 用户信息表
type Person struct {
Id int
FirstName string `db:"first_name"`
LastName string `db:"last_name"`
Email string `db:"email"`
}插入操作(单条/批量插入)
sqlStr := "insert into person(first_name, last_name, email) values (?,?,?)"
ret, err := DB.Exec(sqlStr, "Jason", "Moron", "[email protected]")
if err != nil {
fmt.Println("插入出错", err)
return
}
theID, err := ret.LastInsertId() // 新插入数据的id
if err != nil {
fmt.Println("获取插入的id错误:", err)
return
}
fmt.Println("插入成功,id为:", theID)
ret, err = DB.NamedExec("INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)",
&Person{FirstName: "Jane", LastName: "Citizen",
Email: "[email protected]"})
if err != nil {
fmt.Println("插入出错", err)
return
}
theID, err = ret.LastInsertId() // 新插入数据的id
if err != nil {
fmt.Println("获取插入的id错误:", err)
return
}
fmt.Println("插入成功,id为:", theID)
// batch insert with structs
personStructs := []Person{
{FirstName: "Ardie0", LastName: "Savea", Email: "[email protected]"},
{FirstName: "Sonny Bill0", LastName: "Williams", Email: "[email protected]"},
{FirstName: "Ngani0", LastName: "Laumape", Email: "[email protected]"},
}
ret, err = DB.NamedExec(`INSERT INTO person (first_name, last_name, email)
VALUES (:first_name, :last_name, :email)`, personStructs)
if err != nil {
fmt.Println("批量插入出错", err)
return
}
affectRows, err := ret.RowsAffected()
fmt.Printf("affect rows:%d, err=%v \n", affectRows, err)事务操作
// batch insert with maps
personMaps := []map[string]interface{}{
{"first_name": "Ardie1", "last_name": "Savea",
"email": "[email protected]"},
{"first_name": "Sonny Bill1", "last_name": "Williams",
"email": "[email protected]"},
{"first_name": "Ngani1", "last_name": "Laumape",
"email": "[email protected]"},
}
// 开启事务
tx, err := DB.Beginx()
_, err = tx.NamedExec(`INSERT INTO person (first_name, last_name, email)
VALUES (:first_name, :last_name, :email)`, personMaps)
if err != nil {
// 出错就回滚
tx.Rollback()
fmt.Println("批量插入出错", err)
return
}
tx.Commit()
查询操作(单条/多条记录查询)
// 2. 查询数据
sqlStr = "SELECT * FROM person WHERE last_name=:last_name"
// 使用map做命名查询
rows, _ := DB.NamedQuery(sqlStr, map[string]interface{}{"last_name": "Savea"})
defer rows.Close()
for rows.Next() {
var m Person
rows.StructScan(&m)
fmt.Println(m)
}
// 使用结构体做命名查询
var person = Person{LastName: "Savea"}
rows, _ = DB.NamedQuery(sqlStr, person)
defer rows.Close()
for rows.Next() {
var p Person
rows.StructScan(&p)
fmt.Println(p)
}Get/Select操作
// Get 查询
var personGet Person
err = DB.Get(&personGet, "select * from person where id=?", 1)
if err != nil {
fmt.Println("查询出错", err)
}
fmt.Println(personGet)
// Select 查询
var persons []Person
err = DB.Select(&persons, "select * from person where id > ?", 1)
if err != nil {
fmt.Println("查询出错", err)
}
fmt.Println(persons)更新数据
// 3 修改数据
sqlStr = "update person set last_name= ? where id = ?"
ret, err = DB.Exec(sqlStr, "Savea", 1)
if err != nil {
fmt.Println("更新失败", err)
return
}
n, err := ret.RowsAffected()
if err != nil {
fmt.Println("获取影响的行数失败:", err)
return
}
fmt.Println("更新成功,影响行数为:", n)删除数据
sqlStr = "delete from person where id = ?"
ret, err = DB.Exec(sqlStr, 1)
if err != nil {
fmt.Println("删除出错:", err)
return
}
n, err = ret.RowsAffected() // 操作影响的行数
if err != nil {
fmt.Println("获取操作影响的行数出错:", err)
return
}
fmt.Println("删除成功,影响的行数为:", n)边栏推荐
- 一道golang中defer和函数结合的面试题
- Recommend a website that converts curl commands into PHP code & a website that initiates and executes curl requests online
- 牛客-TOP101-BM38
- MPI学习笔记(二):矩阵相乘的两种实现方法
- Success factors of software R & D effectiveness measurement
- C language file reading and writing
- How to use buffer queue to realize high concurrent order business (glory Collection Edition)
- leetcode-919:完全二叉树插入器
- Automated testing ----- selenium (I)
- 7.23
猜你喜欢

Jmeter分布式压测

Leetcode-155: minimum stack

Focus on data | Haitai Fangyuan directly hits the construction idea of data security governance in the securities industry

The onnx model is exported as a TRT model

leetcode-6131:不可能得到的最短骰子序列

Sum of two numbers and three numbers

Miscellaneous notes -- a hodgepodge
![[online tutorial] iptables official tutorial -- learning notes 2](/img/7d/5f8328d1b4c8878f17c95d2658d2d6.jpg)
[online tutorial] iptables official tutorial -- learning notes 2

Learn FPGA from the bottom structure (16) -- customization and testing of pll/mmcm IP

leetcode-6127:优质数对的数目
随机推荐
Qixin Jushi cloud spectrum new chapter | Haitai Fangyuan and Sichuan Unicom reach ecological strategic cooperation
Hello, I'd like to ask questions about C and database operation.
Introduction to several scenarios involving programming operation of Excel in SAP implementation project
Behind every piece of information you collect, you can't live without TA
Illustration leetcode - 3. longest substring without repeated characters (difficulty: medium)
Leetcode-6125: equal row and column pairs
Open source SPL enhances mangodb computing
Miscellaneous notes -- a hodgepodge
yuv422转rgb(422sp转420p)
Use Navicat to connect to MySQL database through SSH channel (pro test is feasible)
Jmeter分布式压测
Leetcode-155: minimum stack
MySQL inserts three tables with different values. The association condition is the primary foreign key. How about the syntax of the insertion statement?
Opencv learning Fourier transform experience and line direction Fourier transform code
leetcode-919:完全二叉树插入器
Leetcode-6127: number of high-quality pairs
Leetcode-919: complete binary tree inserter
Learn FPGA from the bottom structure (16) -- customization and testing of pll/mmcm IP
作为测试,如何理解线程同步异步
Vulnhub | dc: 6 | [actual combat]