droptableifexistsuser;createtableuser(
id intprimarykeyauto_increment,
name varchar(36),
age int)engine=innodbcharacterset utf8mb4;insertintouser(name, age)values('张三',23),('张三2',23),('张三3',23);
基本增删改查
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"`}funcmain(){// 连接
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
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"`}funcmain(){// 连接
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
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"`}funcmain(){// 连接
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)}}
事务处理
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"`}funcmain(){// 连接
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}deferfunc(){if p :=recover(); p !=nil{_= tx.Rollback()panic(p)}elseif 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}
批量添加
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"`}funcmain(){// 连接
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)}}