1 简介

使用第三方开源的mysql库:

github.com/go-sql-driver/mysql (mysql驱动) github.com/jmoiron/sqlx (基于mysql驱动的封装)

命令行输入 :

go get github.com/go-sql-driver/mysql go get github.com/jmoiron/sqlx

连接mysql:

database, err := sqlx.Open(“mysql”, “root:XXXX@tcp(127.0.0.1:3306)/test”) //database, err := sqlx.Open(“数据库类型”, “用户名:密码@tcp(地址:端口)/数据库名”)

2 连接mysql

  1. var Db *sqlx.DB
  2. // 1 连接
  3. func init() {
  4. db, err := sqlx.Open("mysql", "root:123456@tcp(47.108.170.195:3306)/test")
  5. if err != nil {
  6. fmt.Println("open mysql failed,", err)
  7. return
  8. }
  9. Db = db
  10. }

3 执行SQL语句

新建test数据库

create database test;

  1. // 2 执行DDL语句
  2. func ExecSQL() {
  3. var sql = `
  4. CREATE TABLE person (
  5. first_name text,
  6. last_name text,
  7. email text
  8. );`
  9. Db.Exec(sql)
  10. sql = `
  11. CREATE TABLE place (
  12. country text,
  13. city text NULL,
  14. telcode integer
  15. );`
  16. Db.Exec(sql)
  17. }

4 增删改查

  1. type Person struct {
  2. FirstName string `db:"first_name"`
  3. LastName string `db:"last_name"`
  4. Email string
  5. }
  6. type Place struct {
  7. Country string
  8. City sql.NullString
  9. TelCode int
  10. }

(1) Insert操作

  1. // 3 插入
  2. func Insert() {
  3. tx := Db.MustBegin()
  4. tx.MustExec("INSERT INTO person (first_name, last_name, email) VALUES (?, ?, ?)", "Jason", "Moiron", "jmoiron@jmoiron.net")
  5. tx.MustExec("INSERT INTO person (first_name, last_name, email) VALUES (?, ?, ?)", "John", "Doe", "johndoeDNE@gmail.net")
  6. tx.MustExec("INSERT INTO place (country, city, telcode) VALUES (?, ?, ?)", "United States", "New York", nil)
  7. tx.MustExec("INSERT INTO place (country, city, telcode) VALUES (?, ?)", "China", "Hong Kong", "852")
  8. tx.MustExec("INSERT INTO place (country, telcode) VALUES (?, ?)", "Singapore", "65")
  9. // Named queries can use structs
  10. tx.NamedExec("INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)", &Person{"Jane", "Citizen", "jane.citzen@example.com"})
  11. tx.Commit()
  12. }

(2) Select操作

  1. // 4 查询
  2. func Select() {
  3. // (1) 查询数据库, 存储结果集在 []Person
  4. people := []Person{}
  5. Db.Select(&people, "SELECT * FROM person ORDER BY first_name ASC")
  6. jason, john := people[0], people[1]
  7. fmt.Printf("%#v\n%#v", jason, john)
  8. // Person{FirstName:"Jason", LastName:"Moiron", Email:"jmoiron@jmoiron.net"}
  9. // Person{FirstName:"John", LastName:"Doe", Email:"johndoeDNE@gmail.net"}
  10. // (2) 获取单个结果
  11. jason = Person{}
  12. Db.Get(&jason, "SELECT * FROM person WHERE first_name=?", "Jason")
  13. fmt.Printf("%#v\n", jason)
  14. // Person{FirstName:"Jason", LastName:"Moiron", Email:"jmoiron@jmoiron.net"}
  15. // (3) 使用一个结构体来循环查询
  16. place := Place{}
  17. rows, _ := Db.Queryx("SELECT * FROM place")
  18. for rows.Next() {
  19. err := rows.StructScan(&place)
  20. if err != nil {
  21. log.Fatalln(err)
  22. }
  23. fmt.Printf("%#v\n", place)
  24. }
  25. // Place{Country:"United States", City:sql.NullString{String:"New York", Valid:true}, TelCode:1}
  26. // Place{Country:"Hong Kong", City:sql.NullString{String:"", Valid:false}, TelCode:852}
  27. // Place{Country:"Singapore", City:sql.NullString{String:"", Valid:false}, TelCode:65}
  28. // (4) 批量插入
  29. personMaps := []map[string]interface{}{
  30. {"first_name": "Ardie", "last_name": "Savea", "email": "asavea@ab.co.nz"},
  31. {"first_name": "Sonny Bill", "last_name": "Williams", "email": "sbw@ab.co.nz"},
  32. {"first_name": "Ngani", "last_name": "Laumape", "email": "nlaumape@ab.co.nz"},
  33. }
  34. _, _ = Db.NamedExec(`INSERT INTO person (first_name, last_name, email)
  35. VALUES (:first_name, :last_name, :email)`, personMaps)
  36. }

(3) Update操作

  1. // 5 修改
  2. func Update() {
  3. res, _ := Db.Exec("UPDATE person set first_name=? where email=?", "ws", "sbw@ab.co.nz")
  4. row, _ := res.RowsAffected()
  5. fmt.Println("update succ:", row)
  6. }

(4) Delete操作

  1. // 6 删除
  2. func Delete() {
  3. res, _ := Db.Exec("DELETE FROM person where first_name=?", "ws")
  4. row, _ := res.RowsAffected()
  5. fmt.Println("delete succ: ", row)
  6. }