在项目中我们通常可能会使用database/sql连接MySQL数据库。
本文使用sqlx实现批量插入数据的例子,介绍了sqlx中可能被你忽视了的sqlx.In和DB.NamedExec方法。
在项目中我们通常可能会使用database/sql连接MySQL数据库。sqlx可以认为是Go语言内置database/sql的超集,它在优秀的内置database/sql基础上提供了一组扩展。这些扩展中除了大家常用来查询的Get(dest interface{}, …) error和Select(dest interface{}, …) error外还有很多其他强大的功能。
1.安装sqlx
go get github.com/jmoiron/sqlx
import (
"fmt"
"github.com/jmoiron/sqlx"
_ "github.com/go-sql-driver/mysql"
)
var db *sqlx.DB
func initDB() (err error) {
dsn := "root:123456@tcp(127.0.0.1:3306)/sql_test?charset=utf8mb4&parseTime=True"
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)
return
}
2.查询
当db.Get(&u,sql,id)执行时,sqlx包中会访问结构体u中的各字段,这时发现字段全部为小写,不可访问。
单行查询
type user struct {
ID int
Name string
Age int
}f
unc queryRowDemo() {
sqlStr := "select id, name, age from user where id=?"
var u user
err := db.Get(&u,sqlStr,1)
if err != nil {
fmt.Printf("get failed, err:%v\n", err)
return
}
fmt.Printf("id:%d name:%s age:%d\n", u.ID, u.Name, u.Age)
}
多行查询
func queryMultiRowDemo() {
sqlStr := "select id, name, age from user where id > ?"
var users []user
err := db.Select(&users,sqlStr,0)
if err != nil {
fmt.Printf("query failed, err:%v\n", err)
return
}
fmt.Printf("id:%#v\n", users)
}
3.插入、更新和删除
sqlx中的exec方法与原生sql中的exec使用基本一致:
type user struct {
ID int
Name string
Age int
}
var db *sqlx.DB
func insertRowDemo() {
sqlStr := "insert into user(name,age)values (?,?)"
result, err := db.Exec(sqlStr, "cheng", "45")
if err != nil {
fmt.Printf("insert failed,err:%v\n",err)
return
}
id, err := result.LastInsertId()
if err != nil {
fmt.Printf("get lastinsert ID failed, err:%v\n", err)
return
}
fmt.Printf("insert success,id:%d\n",id)
}
var db *sqlx.DB
func updateRowDemo() {
sqlStr := "update user set age = ? where id = ?"
result, err := db.Exec(sqlStr, 45, 1)
if err != nil {
fmt.Printf("update failed, err:%v\n", err)
return
}
n, err := result.RowsAffected()
if err != nil {
fmt.Printf("get RowsAffected failed, err:%v\n", err)
return
}
fmt.Printf("update success, affected rows:%d\n", n)
}
func deleteRowDemo() {
sqlStr := "delete from user where id = ?"
result, err := db.Exec(sqlStr, 1)
if err != nil {
fmt.Printf("delete failed, err:%v\n", err)
return
}
n, err := result.RowsAffected()
if err != nil {
fmt.Printf("get RowsAffected failed, err:%v\n", err)
return
}
fmt.Printf("delete success, affected rows:%d\n", n)
}
4.NamedQuery
DB.NamedExec方法用来绑定SQL语句与结构体或map中的同名字段
func insertUserDemo()(err error) {
sqlStr :="insert into user (name,age) values(:name,:age)"
_, err = db.NamedExec(sqlStr,
map[string]interface{}{
"name": "cheng",
"age": 50,
})
return err
}
5.NamedQuery
与DB.NamedExec同理,这里是支持查询
func namedQuery() {
sqlStr := "select * from user where name=:name"
rows, err := db.NamedQuery(sqlStr, map[string]interface{}{"name": "cheng"})
if err != nil {
fmt.Printf("db.NamedQuery failed, err:%v\n", err)
return
}
defer rows.Close()
for rows.Next(){
var u user
err := rows.StructScan(&u)
if err != nil {
fmt.Printf("scan failed, err:%v\n", err)
continue
}
fmt.Printf("user:%#v\n", u)
}
}
func nameQuery() {
sqlStr := "select * from user where name=:name"
u := user{
Name: "cheng",
}
rows, err := db.NamedQuery(sqlStr, &u)
if err != nil {
fmt.Printf("db.NamedQuery failed, err:%v\n", err)
return
}
defer rows.Close()
for rows.Next(){
var u user
err := rows.StructScan(&u)
if err != nil {
fmt.Printf("scan failed, err:%v\n", err)
continue
}
fmt.Printf("user:%#v\n",u)
}
}
6.事务操作
对于事务操作,我们可以使用sqlx中提供的db.Beginx()和tx.Exec()方法。
func transcation() (err error) {
tx, err := db.Beginx() //开启事务
if err != nil {
fmt.Printf("begin trans failed, err:%v\n", err)
return err
}
defer func() {
if p := recover();p!=nil {
tx.Rollback()
fmt.Println("rollback1")
panic(p)
}else if err != nil{
fmt.Println("rollback2")
tx.Rollback() //事务回滚
}else {
tx.Commit()
fmt.Println("commit") //事务提交
}
}()
sqlStr1 := "update user set age = 20 where id = ?"
result, err := tx.Exec(sqlStr1, 2)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return errors.New("exec failed")
}
sqlStr2 := "Update user set age=50 where id=?"
result, err = tx.Exec(sqlStr2, 5)
if err!=nil{
return err
}
n, err = result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return errors.New("exec failed")
}
return err
}