当前位置:网站首页>Sqlx library usage
Sqlx library usage
2022-07-25 21:00:00 【Johns】
Introduce
sqlx Is based on Go built-in database/sql Extensions on packages , Mainly to simplify sql Process of use , sqlx Of sql.DB, sql.TX, sql.Stmt Keep the underlying implementation unchanged , Therefore, it can be easily from database/sql Switch to sqlx.sqlx In addition, it also provides some functions :
- Can be Rows The content is parsed to struct( Support embedded )、map、slice
- Named parameters support
- Get/Select You can quickly turn the query results into struct/slice
Installation and connection
go get github.com/jmoiron/sqlximport (
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
func main(){
// Connect to database
// Only sqlx.Open() Function to create a connection pool , At this time, only the connection pool is initialized , No connection to database .
// Connections are inert , Only a call sqlx.DB Method time ,
// At this time, the connection is really used , The connection pool will create connections .
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)
}
// Connection pool configuration
DB.SetMaxIdleConns(100)
DB.SetMaxOpenConns(500)
DB.SetConnMaxIdleTime(5*time.Minute)
}Table and table instance definitions
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 User information sheet
type Person struct {
Id int
FirstName string `db:"first_name"`
LastName string `db:"last_name"`
Email string `db:"email"`
}The insert ( Single / Batch insert )
sqlStr := "insert into person(first_name, last_name, email) values (?,?,?)"
ret, err := DB.Exec(sqlStr, "Jason", "Moron", "[email protected]")
if err != nil {
fmt.Println(" Error inserting ", err)
return
}
theID, err := ret.LastInsertId() // Newly inserted data id
if err != nil {
fmt.Println(" Get inserted id error :", err)
return
}
fmt.Println(" Insert the success ,id by :", 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(" Error inserting ", err)
return
}
theID, err = ret.LastInsertId() // Newly inserted data id
if err != nil {
fmt.Println(" Get inserted id error :", err)
return
}
fmt.Println(" Insert the success ,id by :", 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(" Batch insert error ", err)
return
}
affectRows, err := ret.RowsAffected()
fmt.Printf("affect rows:%d, err=%v \n", affectRows, err)The transaction operations
// 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]"},
}
// Open transaction
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 {
// Roll back if an error occurs
tx.Rollback()
fmt.Println(" Batch insert error ", err)
return
}
tx.Commit()
Query operation ( Single / Multiple records query )
// 2. Query data
sqlStr = "SELECT * FROM person WHERE last_name=:last_name"
// Use map Make a named query
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)
}
// Use structure to make naming query
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 operation
// Get Inquire about
var personGet Person
err = DB.Get(&personGet, "select * from person where id=?", 1)
if err != nil {
fmt.Println(" Query error ", err)
}
fmt.Println(personGet)
// Select Inquire about
var persons []Person
err = DB.Select(&persons, "select * from person where id > ?", 1)
if err != nil {
fmt.Println(" Query error ", err)
}
fmt.Println(persons)Update data
// 3 Modifying data
sqlStr = "update person set last_name= ? where id = ?"
ret, err = DB.Exec(sqlStr, "Savea", 1)
if err != nil {
fmt.Println(" Update failed ", err)
return
}
n, err := ret.RowsAffected()
if err != nil {
fmt.Println(" Failed to get the number of affected rows :", err)
return
}
fmt.Println(" The update is successful , The number of affected lines is :", n)Delete data
sqlStr = "delete from person where id = ?"
ret, err = DB.Exec(sqlStr, 1)
if err != nil {
fmt.Println(" Error deleting :", err)
return
}
n, err = ret.RowsAffected() // Number of rows affected by operation
if err != nil {
fmt.Println(" Error getting the number of rows affected by the operation :", err)
return
}
fmt.Println(" Delete successful , The number of rows affected is :", n)边栏推荐
- What's special about Huawei's innovative solutions to consolidate the foundation of ERP for small and medium-sized enterprises?
- yuv422转rgb(422sp转420p)
- leetcode-6131:不可能得到的最短骰子序列
- LeetCode刷题——猜数字大小II#375#Medium
- 使用oap切面导致controller被重复调用
- Remote - actual combat
- Based on pexels image material API, sort out the material resource library
- process.env
- 接口测试工具 restlet client
- DDD go practice
猜你喜欢

Add startup software items when the win system starts up

Detailed explanation of document operation

leetcode-6125:相等行列对

Debugged PEB (beingdebugged, ntglobalflag)

If the order is not paid for 30 minutes, it will be automatically cancelled. How to achieve this? (Collection Edition)
![[MCU] 51 MCU burning those things](/img/fa/8f11ef64a18114365c084fff7d39f6.png)
[MCU] 51 MCU burning those things

leetcode-155:最小栈

基于腾讯地图实现精准定位,实现微信小程序考勤打卡功能

Matlab---eeglab check EEG signal
![[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
随机推荐
wokerman 自定义写入日志文件
How to obtain the subordinate / annotation information of KEGG channel
7.23
Leetcode skimming -- guess the size of numbers II 375 medium
Pycharm跑程序时自动进入测试模式
leetcode-146:LRU 缓存
数据库sql语句练习题「建议收藏」
zigbee物联网开发平台(工业物联网)
Leetcode-6125: equal row and column pairs
Canvas 填充渐变
Airtest解决“自动装包”过程中需要输入密码的问题(同适用于随机弹框处理)
两数,三数之和
Scan delete folder problems
leetcode-919:完全二叉树插入器
In June 2021, the interview suffered a Waterloo. Is it so convoluted now
Question and answer 47: geeks have an appointment - the current monitoring system construction of CSC
An interview question about concurrent reading and writing of map in golang
day04_ array
Wokerman custom write log file
Introduction to MySQL engine and InnoDB logical storage structure