Golang处理MySQL框架zdpgo_sqlx快速入门教程

准备SQL

sql 复制代码
drop table if exists user;
create table user
(
    id   int primary key auto_increment,
    name varchar(36),
    age  int
) engine = innodb
  character set utf8mb4;

insert into user(name, age)
values ('张三', 23),
       ('张三2', 23),
       ('张三3', 23);

基本增删改查

go 复制代码
package main

import (
	"fmt"
	_ "zdpgo_mysqldriver"
	"zdpgo_sqlx"
)

var (
	db  *zdpgo_sqlx.DB
	err error
)

type user struct {
	Id   int    `db:"id"`
	Age  int    `db:"age"`
	Name string `db:"name"`
}

func main() {
	// 连接
	dsn := "root:zhangdapeng520@tcp(192.168.234.130:3306)/test"
	db, err = zdpgo_sqlx.Open("mysql", dsn)
	if err != nil {
		fmt.Printf("connect server failed, err:%v\n", err)
		return
	}
	db.SetMaxOpenConns(200)
	db.SetMaxIdleConns(10)

	// 新增
	sqlStr := "INSERT INTO user(name, age) VALUES(?, ?)"
	result, err := db.Exec(sqlStr, "张三", 22)
	if err != nil {
		fmt.Printf("exec failed, err:%v\n", err)
		return
	}
	insertID, err := result.LastInsertId()
	if err != nil {
		fmt.Printf("get insert id failed, err:%v\n", err)
		return
	}
	fmt.Printf("insert data success, id:%d\n", insertID)

	// 查询单个
	sqlStr = "SELECT id, name, age FROM user WHERE id = ?"
	var u user
	if err := db.Get(&u, sqlStr, 1); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		return
	}
	fmt.Printf("id:%d, name:%s, age:%d\n", u.Id, u.Name, u.Age)

	// 查询多个
	sqlStr = "SELECT id, name, age FROM user WHERE id > ?"
	var users []user
	if err := db.Select(&users, sqlStr, 0); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		return
	}
	for i := 0; i < len(users); i++ {
		fmt.Printf("id:%d, name:%s, age:%d\n", users[i].Id, users[i].Name, users[i].Age)
	}

	// 更新
	sqlStr = "UPDATE user SET age = ? WHERE id = ?"
	result, err = db.Exec(sqlStr, 22, 1)
	if err != nil {
		fmt.Printf("exec failed, err:%v\n", err)
		return
	}
	affectedRows, err := result.RowsAffected()
	if err != nil {
		fmt.Printf("get affected failed, err:%v\n", err)
		return
	}
	fmt.Printf("update data success, affected rows:%d\n", affectedRows)

	// 删除
	sqlStr = "DELETE FROM user WHERE id = ?"
	result, err = db.Exec(sqlStr, 1)
	if err != nil {
		fmt.Printf("exec failed, err:%v\n", err)
		return
	}
	affectedRows, err = result.RowsAffected()
	if err != nil {
		fmt.Printf("get affected failed, err:%v\n", err)
		return
	}
	fmt.Printf("delete data success, affected rows:%d\n", affectedRows)
}

NamedQuery

go 复制代码
package main

import (
	"fmt"
	_ "zdpgo_mysqldriver"
	"zdpgo_sqlx"
)

var (
	db  *zdpgo_sqlx.DB
	err error
)

type user struct {
	Id   int    `db:"id"`
	Age  int    `db:"age"`
	Name string `db:"name"`
}

func main() {
	// 连接
	dsn := "root:zhangdapeng520@tcp(192.168.234.130:3306)/test"
	db, err = zdpgo_sqlx.Open("mysql", dsn)
	if err != nil {
		fmt.Printf("connect server failed, err:%v\n", err)
		return
	}
	db.SetMaxOpenConns(200)
	db.SetMaxIdleConns(10)

	sqlStr := "SELECT id, name, age FROM user WHERE age = :age"
	rows, err := db.NamedQuery(sqlStr, map[string]interface{}{
		"age": 23,
	})
	if err != nil {
		fmt.Printf("named query failed failed, err:%v\n", err)
		return
	}
	defer rows.Close()
	for rows.Next() {
		var u user
		if err := rows.StructScan(&u); err != nil {
			fmt.Printf("struct sacn failed, err:%v\n", err)
			continue
		}
		fmt.Printf("%#v\n", u)
	}
}

NamedExec

go 复制代码
package main

import (
	"fmt"
	_ "zdpgo_mysqldriver"
	"zdpgo_sqlx"
)

var (
	db  *zdpgo_sqlx.DB
	err error
)

type user struct {
	Id   int    `db:"id"`
	Age  int    `db:"age"`
	Name string `db:"name"`
}

func main() {
	// 连接
	dsn := "root:zhangdapeng520@tcp(192.168.234.130:3306)/test"
	db, err = zdpgo_sqlx.Open("mysql", dsn)
	if err != nil {
		fmt.Printf("connect server failed, err:%v\n", err)
		return
	}
	db.SetMaxOpenConns(200)
	db.SetMaxIdleConns(10)

	sqlStr := "INSERT INTO user(name, age) VALUES(:name, :age)"
	result, err := db.NamedExec(sqlStr, map[string]interface{}{
		"name": "里斯",
		"age":  18,
	})
	if err != nil {
		fmt.Printf("named exec failed, err:%v\n", err)
		return
	}
	insertId, err := result.LastInsertId()
	if err != nil {
		fmt.Printf("get last insert id failed, err:%v\n", err)
		return
	}
	fmt.Printf("insert data success, id:%d\n", insertId)

	sqlStr = "SELECT id, name, age FROM user WHERE age = :age"
	rows, err := db.NamedQuery(sqlStr, map[string]interface{}{
		"age": 18,
	})
	if err != nil {
		fmt.Printf("named query failed failed, err:%v\n", err)
		return
	}
	defer rows.Close()
	for rows.Next() {
		var u user
		if err := rows.StructScan(&u); err != nil {
			fmt.Printf("struct sacn failed, err:%v\n", err)
			continue
		}
		fmt.Printf("%#v\n", u)
	}
}

事务处理

go 复制代码
package main

import (
	"fmt"
	_ "zdpgo_mysqldriver"
	"zdpgo_sqlx"
)

var (
	db  *zdpgo_sqlx.DB
	err error
)

type user struct {
	Id   int    `db:"id"`
	Age  int    `db:"age"`
	Name string `db:"name"`
}

func main() {
	// 连接
	dsn := "root:zhangdapeng520@tcp(192.168.234.130:3306)/test"
	db, err = zdpgo_sqlx.Open("mysql", dsn)
	if err != nil {
		fmt.Printf("connect server failed, err:%v\n", err)
		return
	}
	db.SetMaxOpenConns(200)
	db.SetMaxIdleConns(10)

	tx, err := db.Begin()
	if err != nil {
		fmt.Printf("transaction begin failed, err:%v\n", err)
		return
	}

	defer func() {
		if p := recover(); p != nil {
			_ = tx.Rollback()
			panic(p)
		} else if err != nil {
			fmt.Printf("transaction rollback")
			_ = tx.Rollback()
		} else {
			err = tx.Commit()
			fmt.Printf("transaction commit")
			return
		}
	}()

	sqlStr1 := "UPDATE user SET age = ? WHERE id = ? "
	reuslt1, err := tx.Exec(sqlStr1, 18, 1)
	if err != nil {
		fmt.Printf("sql exec failed, err:%v\n", err)
		return
	}
	rows1, err := reuslt1.RowsAffected()
	if err != nil {
		fmt.Printf("affected rows is 0")
		return
	}
	sqlStr2 := "UPDATE user SET age = ? WHERE id = ? "
	reuslt2, err := tx.Exec(sqlStr2, 19, 5)
	if err != nil {
		fmt.Printf("sql exec failed, err:%v\n", err)
		return
	}
	rows2, err := reuslt2.RowsAffected()
	if err != nil {
		fmt.Printf("affected rows is 0\n")
		return
	}

	if rows1 > 0 && rows2 > 0 {
		fmt.Printf("update data success\n")
	}
	return
}

批量添加

go 复制代码
package main

import (
	"fmt"
	_ "zdpgo_mysqldriver"
	"zdpgo_sqlx"
)

var (
	db  *zdpgo_sqlx.DB
	err error
)

type User struct {
	Id   int    `db:"id"`
	Age  int    `db:"age"`
	Name string `db:"name"`
}

type AddUser struct {
	Age  int    `db:"age"`
	Name string `db:"name"`
}

func main() {
	// 连接
	dsn := "root:zhangdapeng520@tcp(192.168.234.130:3306)/test"
	db, err = zdpgo_sqlx.Open("mysql", dsn)
	if err != nil {
		fmt.Printf("connect server failed, err:%v\n", err)
		return
	}
	db.SetMaxOpenConns(200)
	db.SetMaxIdleConns(10)

	// 准备数据
	u1 := AddUser{Name: "李四1", Age: 18}
	u2 := AddUser{Name: "李四2", Age: 28}
	u3 := AddUser{Name: "李四3", Age: 38}
	users := []interface{}{u1, u2, u3}

	_, err = db.NamedExec("INSERT INTO user (name, age) VALUES (:name, :age)", users)
	fmt.Println(err)
	return
}
···

## in 查询
```go
package main

import (
	"fmt"
	_ "zdpgo_mysqldriver"
	"zdpgo_sqlx"
)

var (
	db  *zdpgo_sqlx.DB
	err error
)

type User struct {
	Id   int    `db:"id"`
	Age  int    `db:"age"`
	Name string `db:"name"`
}

type AddUser struct {
	Age  int    `db:"age"`
	Name string `db:"name"`
}

func main() {
	// 连接
	dsn := "root:zhangdapeng520@tcp(192.168.234.130:3306)/test"
	db, err = zdpgo_sqlx.Open("mysql", dsn)
	if err != nil {
		fmt.Printf("connect server failed, err:%v\n", err)
		return
	}
	db.SetMaxOpenConns(200)
	db.SetMaxIdleConns(10)

	// 动态填充id
	ids := []int{1, 2, 3}
	query, args, err := zdpgo_sqlx.In("SELECT name, age FROM user WHERE id IN (?)", ids)
	if err != nil {
		panic(err)
	}

	// sqlx.In 返回带 `?` bindvar的查询语句, 我们使用Rebind()重新绑定。
	// 重新生成对应数据库的查询语句(如PostgreSQL 用 `$1`, `$2` bindvar)
	query = db.Rebind(query)
	var users []User
	err = db.Select(&users, query, args...)
	if err != nil {
		panic(err)
	}
	for _, user := range users {
		fmt.Printf("user:%#v\n", user)
	}
}
相关推荐
向前看-42 分钟前
验证码机制
前端·后端
超爱吃士力架2 小时前
邀请逻辑
java·linux·后端
AskHarries4 小时前
Spring Cloud OpenFeign快速入门demo
spring boot·后端
isolusion5 小时前
Springboot的创建方式
java·spring boot·后端
zjw_rp6 小时前
Spring-AOP
java·后端·spring·spring-aop
TodoCoder6 小时前
【编程思想】CopyOnWrite是如何解决高并发场景中的读写瓶颈?
java·后端·面试
凌虚7 小时前
Kubernetes APF(API 优先级和公平调度)简介
后端·程序员·kubernetes
机器之心7 小时前
图学习新突破:一个统一框架连接空域和频域
人工智能·后端
.生产的驴8 小时前
SpringBoot 对接第三方登录 手机号登录 手机号验证 微信小程序登录 结合Redis SaToken
java·spring boot·redis·后端·缓存·微信小程序·maven
顽疲8 小时前
springboot vue 会员收银系统 含源码 开发流程
vue.js·spring boot·后端