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)
	}
}
相关推荐
tyler_download7 分钟前
golang 实现比特币内核:处理椭圆曲线中的天文数字
golang·blockchain·bitcoin
代码之光_19801 小时前
保障性住房管理:SpringBoot技术优势分析
java·spring boot·后端
ajsbxi1 小时前
苍穹外卖学习记录
java·笔记·后端·学习·nginx·spring·servlet
疯狂的程需猿1 小时前
一个百度、必应搜索引擎图片获取下载的工具包
golang·图搜索
颜淡慕潇2 小时前
【K8S问题系列 |1 】Kubernetes 中 NodePort 类型的 Service 无法访问【已解决】
后端·云原生·容器·kubernetes·问题解决
明月看潮生3 小时前
青少年编程与数学 02-003 Go语言网络编程 09课题、Cookie
青少年编程·golang·网络编程·编程与数学
尘浮生3 小时前
Java项目实战II基于Spring Boot的光影视频平台(开发文档+数据库+源码)
java·开发语言·数据库·spring boot·后端·maven·intellij-idea
尚学教辅学习资料3 小时前
基于SpringBoot的医药管理系统+LW示例参考
java·spring boot·后端·java毕业设计·医药管理
明月看潮生3 小时前
青少年编程与数学 02-003 Go语言网络编程 15课题、Go语言URL编程
开发语言·网络·青少年编程·golang·编程与数学
明月看潮生3 小时前
青少年编程与数学 02-003 Go语言网络编程 14课题、Go语言Udp编程
青少年编程·golang·网络编程·编程与数学