Home  >  Article  >  Backend Development  >  Go language enhanced version operates Mysql (Sqlx)

Go language enhanced version operates Mysql (Sqlx)

Go语言进阶学习
Go语言进阶学习forward
2023-07-24 14:34:331059browse
##mod file

go.mod

module sqlxDemo


go 1.14


require (
    github.com/go-sql-driver/mysql v1.4.0
    github.com/jmoiron/sqlx v1.2.0
    google.golang.org/appengine v1.6.7 // indirect
)

Create data table

Create table code

CREATE TABLE `userinfo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(10) DEFAULT NULL,
  `phone` char(11) DEFAULT NULL,
  `address` varchar(64) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;

Create structure

Structure code

type Userinfo struct {
    Id      int64  `json:"id"`
    Name    string `json:"name"`
    Phone   string `json:"phone"`
    Address string `json:"address"`
}

连接数据库

代码

import (
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jmoiron/sqlx"
)
type Userinfo struct {
    Id      int64  `json:"id"`
    Name    string `json:"name"`
    Phone   string `json:"phone"`
    Address string `json:"address"`
}
func main() {
    dsn := "root:rootroot@tcp(127.0.0.1:3306)/go_mysql_demo?charset=utf8mb4&parseTime=True"
    // 使用 MustConnect 连接的话,验证失败不成功直接panic
    //db := sqlx.MustConnect("mysql", dsn)


    //使用 Connect 连接,会验证是否连接成功,
    db, err := sqlx.Connect("mysql", dsn)


    if err != nil {
        fmt.Printf("connect DB failed, err:%v\n", err)
        return
}
    db.SetMaxOpenConns(20)
    db.SetMaxIdleConns(10)
}

查询单条

我记得使用原来的方式进行查询并且绑定结构体,是这审的。

//查询单条
sqlStr := "SELECT id,`name`,phone,address from userinfo where id = ?;"
var user Userinfo
err = db.QueryRow(sqlStr, 1).Scan(&user.Id, &user.Name, &user.Phone, &user.Address)
if err != nil {
    fmt.Println("查询失败", err)
    return
}

第4行代码,需要将结构体的字段一个一个上去。

如果使用sqlx呢?

代码

//查询
sqlStr := "SELECT id,`name`,phone,address from userinfo where id = ?;"
var user Userinfo
err = db.Get(&user, sqlStr, 1)
if err != nil {
    fmt.Println("查询失败:", err)
    return
}
fmt.Println("user:",user)

执行结果

Go language enhanced version operates Mysql (Sqlx)

还是第4行代码,直接一个结构体扔过去,就绑定成功了。

如果表有很多字段,结构体字段也有很多,这个是很有用的。

查询多条

还是惯例,看看原来是怎么查的。

//查询多条
sqlStr := "SELECT id,`name`,phone,address from userinfo where id >= ?"
//参数同 QueryRow
rows, err := db.Query(sqlStr, 1)
//处理err
// 此处使用rows释放所有链接
defer rows.Close()
//循环整理所有数据
var userList = make([]Userinfo, 0, 10)
for rows.Next() {
    var user Userinfo
    err = rows.Scan(&user.Id, &user.Name, &user.Phone, &user.Address)
    //处理err
    userList = append(userList, user)
}
fmt.Println(userList)

为了方便,我去掉了err,使用伪代码处理err代替。

原来的方法,查询出来还得需要一个循环,还需要一个切片,乖乖嘞,打扰了。


来看看sqlx

代码

//查询多条
sqlStr := "SELECT id,`name`,phone,address from userinfo where id >= ?"
var userList []Userinfo
err = db.Select(&userList, sqlStr, 1)
if err != nil {
    fmt.Println("查询失败:", err)
    return
}
fmt.Println("userList:",userList)

执行结果

Go language enhanced version operates Mysql (Sqlx)

还是直接扔过去,就绑定完成了,真是美滋滋。

添加

额,添加,更新,删除,事物的话,似乎跟原来差不多,直接看代码叭。

代码

//添加
sqlStr := "INSERT into userinfo(name,phone,address) values(?,?,?);"
result, err := db.Exec(sqlStr, "吴彦祖", 555, "不知道哪的")
if err != nil {
    fmt.Println("插入失败", err)
    return
}
row_affect, err := result.RowsAffected()
if err != nil {
    fmt.Println("受影响行数获取失败:", err)
    return
}
fmt.Println("受影响的行数:", row_affect)
lastId, err := result.LastInsertId()
if err != nil {
    fmt.Println("新增行id获取失败:", err)
    return
}
fmt.Println("新增行id:", lastId)
fmt.Println("插入成功")

执行结果

Go language enhanced version operates Mysql (Sqlx)

Mysql

Go language enhanced version operates Mysql (Sqlx)

更新

代码

//更新数据
sqlStr := `UPDATE userinfo set name=? where id=?;`
result, err := db.Exec(sqlStr, "吴彦祖666", 4)
if err != nil {
    fmt.Println("更新失败", err)
    return
}
//受影响的行数
row_affect, err := result.RowsAffected()
if err != nil {
    fmt.Println("受影响行数获取失败:", err)
    return
}
fmt.Println("受影响的行数:", row_affect)


fmt.Println("更新成功")

执行结果

Go language enhanced version operates Mysql (Sqlx)

Mysql

Go language enhanced version operates Mysql (Sqlx)

删除

代码

sqlStr := "delete from userinfo where id = ?;"
result, err := db.Exec(sqlStr, 4)
if err != nil {
    fmt.Println("删除失败", err)
    return
}
//受影响的行数
row_affect, err := result.RowsAffected()
if err != nil {
    fmt.Println("受影响行数获取失败:", err)
    return
}
fmt.Println("受影响的行数:", row_affect)


fmt.Println("删除成功")

执行结果

Go language enhanced version operates Mysql (Sqlx)

Mysql

Go language enhanced version operates Mysql (Sqlx)

事物

代码

//事物
tx, err := db.Begin()
if err != nil {
    //释放事物
    if tx != nil {
        tx.Rollback()
}
    fmt.Println("事物开启失败")
    return
}
张三减10块Sql := `UPDATE bill set money=money - 10 where name = ?;`
result, err := tx.Exec(张三减10块Sql, "张三")
if err != nil {
    //有错误表示更是失败,回滚原来状态
    tx.Rollback()
    fmt.Println(err)
    return
}
张三受影响行数, err := result.RowsAffected()
if err != nil {
    tx.Rollback() // 回滚
    return
}


李四加10块Sql := `UPDATE bill set money=money + 10 where name = ?;`
result, err = tx.Exec(李四加10块Sql, "李四")
if err != nil {
    //有错误表示更是失败,回滚原来状态
    tx.Rollback()
    fmt.Println(err)
    return
}
李四受影响行数, err := result.RowsAffected()
if err != nil {
    tx.Rollback() // 回滚
    return
}
//都等于1表示成功,可以提交事务,修改数据
if 张三受影响行数==1 && 李四受影响行数==1{
    //提交事务
    fmt.Println("提交事务")
    tx.Commit()
}else{
    //有一个!=1表示没有更新成功,可能用户不存在
    fmt.Println("失败了,事物回滚了")
    tx.Rollback()
}
fmt.Println("事物执行成功")

执行结果

Go language enhanced version operates Mysql (Sqlx)

Mysql

Go language enhanced version operates Mysql (Sqlx)

NameExec

增 删 改使用。

NameExec方法是通过结构体Map绑定SQL语句,试了试,感觉用处不大,不做举例。

NameQuery

Use for query.

The usage is the same as above, but it is useless, so I won’t give an example.

Summary

In factsqlx module, the biggest improvement In terms of query, I believe you have also seen that is indeed more convenient than native query very many.

But in terms of other convenience, it seems to be stretched, but also said that generally there are many query scenarios, Check more and change less.

The above is the detailed content of Go language enhanced version operates Mysql (Sqlx). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete