当前位置:网站首页>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)边栏推荐
- [FAQ] access the HMS core push service, and the server sends messages. Cause analysis and solutions of common error codes
- Leetcode customs clearance: hash table six, this is really a little simple
- Force deduction ----- calculate the money of the force deduction bank
- Embedded development: embedded foundation -- threads and tasks
- Remote - basic principle introduction
- wokerman 自定义写入日志文件
- Product principles of non-financial decentralized application
- 牛客-TOP101-BM38
- Cesium 多边形渐变色纹理(Canvas)
- Qixin Jushi cloud spectrum new chapter | Haitai Fangyuan and Sichuan Unicom reach ecological strategic cooperation
猜你喜欢

Leetcode skimming -- guess the size of numbers II 375 medium

Leetcode-6127: number of high-quality pairs

程序的编译和运行

Remote—基本原理介绍

DDD go practice

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

Detailed explanation of document operation

Unity VS—— VS中默认调试为启动而不是附加到Unity调试

Online random coin tossing positive and negative statistical tool

Unity vs -- the default debugging in VS is to start rather than attach to unity debugging
随机推荐
A detailed explanation of SCP command
Leetcode-6129: number of all 0 subarrays
Explain in detail the principle of MySQL master-slave replication "suggestions collection"
MySQL master-slave replication data synchronization, summary of common problems
【单细胞高级绘图】07.KEGG富集结果展示
Based on pexels image material API, sort out the material resource library
cts测试步骤(卡西欧cts200测试)
Step num problem
[matlab] download originality documents based on oil monkey script and MATLAB
resize函数的作用「建议收藏」
Canvas 填充渐变
Yolov7 training error indexerror: list index out of range
租房二三事
PayPal PHP product trial period "recommended collection"
An interview question about concurrent reading and writing of map in golang
Has baozi ever played in the multi merchant system?
数据库sql语句练习题「建议收藏」
seven point two three
Product principles of non-financial decentralized application
Explain the principle of MySQL master-slave replication in detail