1. MySQL事务

mysql事务特性:

  1. 1) 原子性
  2. 2) 一致性
  3. 3) 隔离性
  4. 4) 持久性

golang MySQL事务应用:

  1. 1 import (“github.com/jmoiron/sqlx")
  2. 2) Db.Begin() 开始事务
  3. 3) Db.Commit() 提交事务
  4. 4) Db.Rollback() 回滚事务
  1. package main
  2. import (
  3. "fmt"
  4. _ "github.com/go-sql-driver/mysql"
  5. "github.com/jmoiron/sqlx"
  6. )
  7. type Person struct {
  8. UserId int `db:"user_id"`
  9. Username string `db:"username"`
  10. Sex string `db:"sex"`
  11. Email string `db:"email"`
  12. }
  13. type Place struct {
  14. Country string `db:"country"`
  15. City string `db:"city"`
  16. TelCode int `db:"telcode"`
  17. }
  18. var Db *sqlx.DB
  19. func init() {
  20. database, err := sqlx.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test")
  21. if err != nil {
  22. fmt.Println("open mysql failed,", err)
  23. return
  24. }
  25. Db = database
  26. }
  27. func main() {
  28. conn, err := Db.Begin()
  29. if err != nil {
  30. fmt.Println("begin failed :", err)
  31. return
  32. }
  33. r, err := conn.Exec("insert into person(username, sex, email)values(?, ?, ?)", "stu001", "man", "stu01@qq.com")
  34. if err != nil {
  35. fmt.Println("exec failed, ", err)
  36. conn.Rollback()
  37. return
  38. }
  39. id, err := r.LastInsertId()
  40. if err != nil {
  41. fmt.Println("exec failed, ", err)
  42. conn.Rollback()
  43. return
  44. }
  45. fmt.Println("insert succ:", id)
  46. r, err = conn.Exec("insert into person(username, sex, email)values(?, ?, ?)", "stu001", "man", "stu01@qq.com")
  47. if err != nil {
  48. fmt.Println("exec failed, ", err)
  49. conn.Rollback()
  50. return
  51. }
  52. id, err = r.LastInsertId()
  53. if err != nil {
  54. fmt.Println("exec failed, ", err)
  55. conn.Rollback()
  56. return
  57. }
  58. fmt.Println("insert succ:", id)
  59. conn.Commit()
  60. }

输出结果:

  1. insert succ: 2
  2. insert succ: 3

查看MySQL:

  1. mysql> select * from person;
  2. +---------+----------+------+--------------+
  3. | user_id | username | sex | email |
  4. +---------+----------+------+--------------+
  5. | 2 | stu001 | man | stu01@qq.com |
  6. | 3 | stu001 | man | stu01@qq.com |
  7. +---------+----------+------+--------------+
  8. 2 rows in set (0.00 sec)