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)
	}
}
相关推荐
qq_17448285757 小时前
springboot基于微信小程序的旧衣回收系统的设计与实现
spring boot·后端·微信小程序
锅包肉的九珍8 小时前
Scala的Array数组
开发语言·后端·scala
心仪悦悦8 小时前
Scala的Array(2)
开发语言·后端·scala
2401_882727579 小时前
BY组态-低代码web可视化组件
前端·后端·物联网·低代码·数学建模·前端框架
心仪悦悦9 小时前
Scala中的集合复习(1)
开发语言·后端·scala
代码小鑫9 小时前
A043-基于Spring Boot的秒杀系统设计与实现
java·开发语言·数据库·spring boot·后端·spring·毕业设计
真心喜欢你吖10 小时前
SpringBoot与MongoDB深度整合及应用案例
java·spring boot·后端·mongodb·spring
激流丶10 小时前
【Kafka 实战】Kafka 如何保证消息的顺序性?
java·后端·kafka
uzong11 小时前
一个 IDEA 老鸟的 DEBUG 私货之多线程调试
java·后端
飞升不如收破烂~11 小时前
Spring boot常用注解和作用
java·spring boot·后端