当前位置:网站首页>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)边栏推荐
- leetcode-155:最小栈
- Leetcode-155: minimum stack
- kali修改更新源(无法安全的用该源更新)
- Remote - basic principle introduction
- 一道golang中关于接口和实现的面试题
- Huatai Securities account opening process, is it safe to open an account on your mobile phone
- Illustration leetcode - 3. longest substring without repeated characters (difficulty: medium)
- yuv422转rgb(422sp转420p)
- Cesium polygon gradient texture (canvas)
- [MCU] 51 MCU burning those things
猜你喜欢

Detailed explanation of document operation

Too many passwords, don't know how to record? Why don't you write a password box applet yourself
![[paper reading] unpaired image to image translation using cycle consistent advantageous networks](/img/73/69651dd8ecfdddd1cae13a1d223d51.png)
[paper reading] unpaired image to image translation using cycle consistent advantageous networks

Add startup software items when the win system starts up

leetcode-6129:全 0 子数组的数目
![[online tutorial] iptables official tutorial -- learning notes 2](/img/7d/5f8328d1b4c8878f17c95d2658d2d6.jpg)
[online tutorial] iptables official tutorial -- learning notes 2
![[tensorrt] dynamic batch reasoning](/img/59/42ed0074de7162887bfe2c81891e20.png)
[tensorrt] dynamic batch reasoning

Leetcode-6130: designing digital container systems

leetcode-79:单词搜索

How to obtain the subordinate / annotation information of KEGG channel
随机推荐
seven point two three
使用oap切面导致controller被重复调用
Use of C log4net: add file name and line number to the output log content; Repackaged class output file name and line number
[fiddlertx plug-in] use Fiddler to capture the package Tencent classroom video download (unable to capture the package solution)
Basic knowledge of Marine Geology
What's special about Huawei's innovative solutions to consolidate the foundation of ERP for small and medium-sized enterprises?
Differences between seaslog and monolog log systems, installation steps of seaslog [easy to understand]
MySQL master-slave replication data synchronization, summary of common problems
Explain in detail the principle of MySQL master-slave replication "suggestions collection"
Question and answer 47: geeks have an appointment - the current monitoring system construction of CSC
[workplace rules] it workplace rules | poor performance
KEGG通路的从属/注释信息如何获取
When MySQL resets the root password and modifies the password, an error occurs. The password field does not exist
Opencv learning Fourier transform experience and line direction Fourier transform code
Hello, I'd like to ask questions about C and database operation.
一道golang中关于recover的面试题
Principle analysis of bootloader
MPI学习笔记(二):矩阵相乘的两种实现方法
LeetCode通关:哈希表六连,这个还真有点简单
结构体,枚举类型与联合体