# Go使用sqlx操作MySQL完整指南## 1. 安装依赖```bash
go get github.com/go-sql-driver/mysql
go get github.com/jmoiron/sqlx
2. 数据库基础操作
package mainimport ("fmt"_ "github.com/go-sql-driver/mysql""github.com/jmoiron/sqlx"
)
var db *sqlx.DB
type User struct {ID int `db:"id"`Username string `db:"username"`Password string `db:"password"`Age int `db:"age"`
}
func initDB() (err error) {dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True"db, err = sqlx.Connect("mysql", dsn)if err != nil {return err}db.SetMaxOpenConns(100)db.SetMaxIdleConns(10)return nil
}
func createDatabase() error {_, err := db.Exec("CREATE DATABASE IF NOT EXISTS test DEFAULT CHARACTER SET utf8mb4")return err
}
func dropDatabase() error {_, err := db.Exec("DROP DATABASE IF EXISTS test")return err
}
func createTable() error {sql := `CREATE TABLE IF NOT EXISTS users(id INT PRIMARY KEY AUTO_INCREMENT,username VARCHAR(50) NOT NULL UNIQUE,password VARCHAR(50) NOT NULL,age INT)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;`_, err := db.Exec(sql)return err
}
func dropTable() error {_, err := db.Exec("DROP TABLE IF EXISTS users")return err
}
func insertUser(user User) error {sql := "INSERT INTO users(username, password, age) VALUES (?, ?, ?)"_, err := db.Exec(sql, user.Username, user.Password, user.Age)return err
}
func batchInsertUsers(users []User) error {sql := "INSERT INTO users(username, password, age) VALUES (:username, :password, :age)"_, err := db.NamedExec(sql, users)return err
}
func getUserByID(id int) (User, error) {var user Usersql := "SELECT * FROM users WHERE id=?"err := db.Get(&user, sql, id)return user, err
}
func getUsers(age int) ([]User, error) {var users []Usersql := "SELECT * FROM users WHERE age > ?"err := db.Select(&users, sql, age)return users, err
}
func updateUser(user User) error {sql := "UPDATE users SET password=?, age=? WHERE username=?"_, err := db.Exec(sql, user.Password, user.Age, user.Username)return err
}
func deleteUser(id int) error {sql := "DELETE FROM users WHERE id=?"_, err := db.Exec(sql, id)return err
}func main() {if err := initDB(); err != nil {fmt.Printf("init db failed, err:%v\n", err)return}defer db.Close()if err := createDatabase(); err != nil {fmt.Printf("create database failed, err:%v\n", err)return}if err := createTable(); err != nil {fmt.Printf("create table failed, err:%v\n", err)return}user1 := User{Username: "张三",Password: "123456",Age: 20,}if err := insertUser(user1); err != nil {fmt.Printf("insert user failed, err:%v\n", err)return}users := []User{{Username: "李四", Password: "123456", Age: 21},{Username: "王五", Password: "123456", Age: 22},{Username: "赵六", Password: "123456", Age: 23},}if err := batchInsertUsers(users); err != nil {fmt.Printf("batch insert users failed, err:%v\n", err)return}user, err := getUserByID(1)if err != nil {fmt.Printf("get user failed, err:%v\n", err)return}fmt.Printf("user:%#v\n", user)userList, err := getUsers(20)if err != nil {fmt.Printf("get users failed, err:%v\n", err)return}fmt.Printf("users:%#v\n", userList)user1.Password = "654321"if err := updateUser(user1); err != nil {fmt.Printf("update user failed, err:%v\n", err)return}if err := deleteUser(1); err != nil {fmt.Printf("delete user failed, err:%v\n", err)return}if err := dropTable(); err != nil {fmt.Printf("drop table failed, err:%v\n", err)return}if err := dropDatabase(); err != nil {fmt.Printf("drop database failed, err:%v\n", err)return}
}
3. 事务操作示例
func transfer(fromUsername, toUsername string, amount int) error {tx, err := db.Beginx() if err != nil {return err}sql1 := "UPDATE users SET balance = balance - ? WHERE username = ?"sql2 := "UPDATE users SET balance = balance + ? WHERE username = ?"result1, err := tx.Exec(sql1, amount, fromUsername)if err != nil {tx.Rollback() return err}rows1, err := result1.RowsAffected()if err != nil {tx.Rollback()return err}if rows1 != 1 {tx.Rollback()return fmt.Errorf("转出账户不存在")}result2, err := tx.Exec(sql2, amount, toUsername)if err != nil {tx.Rollback()return err}rows2, err := result2.RowsAffected()if err != nil {tx.Rollback()return err}if rows2 != 1 {tx.Rollback()return fmt.Errorf("转入账户不存在")}return tx.Commit()
}
4. 常用查询技巧
4.1 IN查询
func getUsersByIDs(ids []int) ([]User, error) {query, args, err := sqlx.In("SELECT * FROM users WHERE id IN (?)", ids)if err != nil {return nil, err}query = db.Rebind(query)var users []Usererr = db.Select(&users, query, args...)return users, err
}
4.2 分页查询
func getUsersByPage(page, pageSize int) ([]User, error) {offset := (page - 1) * pageSizesql := "SELECT * FROM users LIMIT ? OFFSET ?"var users []Usererr := db.Select(&users, sql, pageSize, offset)return users, err
}
4.3 模糊查询
func searchUsers(keyword string) ([]User, error) {sql := "SELECT * FROM users WHERE username LIKE ?"var users []Usererr := db.Select(&users, sql, "%"+keyword+"%")return users, err
}
5. 注意事项
- 始终记得关闭数据库连接
- 使用事务时要确保正确处理回滚和提交
- 使用预处理语句防止SQL注入
- 合理设置连接池参数
- 处理所有可能的错误
- 使用合适的字段类型和索引优化查询性能
6. 最佳实践
- 使用结构体标签映射数据库字段
- 统一错误处理
- 使用连接池
- 合理组织代码结构
- 编写单元测试
- 记录必要的日志
- 定期备份数据库