当前位置:网站首页>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)边栏推荐
- How to obtain the subordinate / annotation information of KEGG channel
- The database empties the table data and makes the primary key start from 1
- Hello, I'd like to ask questions about C and database operation.
- leetcode-114:二叉树展开为链表
- Remote - basic principle introduction
- Follow up of Arlo's thinking
- 文件操作详解
- The onnx model is exported as a TRT model
- Canvas fill gradient
- Fanoutexchange switch code tutorial
猜你喜欢

The international summit osdi included Taobao system papers for the first time, and end cloud collaborative intelligence was recommended by the keynote speech of the conference

leetcode-79:单词搜索

Pycharm跑程序时自动进入测试模式

How to choose a microservice registration center?
![[FAQ] access the HMS core push service, and the server sends messages. Cause analysis and solutions of common error codes](/img/65/4dd3a521946e753c79d3db1fa0a4f4.png)
[FAQ] access the HMS core push service, and the server sends messages. Cause analysis and solutions of common error codes

程序的编译和运行

Cesium 多边形渐变色纹理(Canvas)
![[advanced drawing of single cell] 07. Display of KEGG enrichment results](/img/60/09c5f44d64b96c6e4d57e5f426e4ed.png)
[advanced drawing of single cell] 07. Display of KEGG enrichment results

ROS_ Rqt toolbox

leetcode-114:二叉树展开为链表
随机推荐
leetcode-6125:相等行列对
基于腾讯地图实现精准定位,实现微信小程序考勤打卡功能
Leetcode-6129: number of all 0 subarrays
Kubernetes advanced part learning notes
Leetcode-919: complete binary tree inserter
Differences between seaslog and monolog log systems, installation steps of seaslog [easy to understand]
结构体,枚举类型与联合体
[matlab] download originality documents based on oil monkey script and MATLAB
Leetcode-79: word search
leetcode-919:完全二叉树插入器
Remote—实战
Pychart automatically enters the test mode when running the program
leetcode-6129:全 0 子数组的数目
作为测试,如何理解线程同步异步
Brush questions with binary tree (4)
Basic knowledge of Marine Geology
Hello, I'd like to ask questions about C and database operation.
Leetcode-6127: number of high-quality pairs
The uniapp project starts with an error binding Node is not a valid Win32 Application ultimate solution
文件操作详解