老男孩IT培训-Go语言操作MySQL(三)
老男孩IT教育
常见问题
2021年4月20日 17:59
MySQL 事务主要用于处理操作量大,复杂度高的数据。在 MySQL 中只有使用了 Innodb 数据库引擎的数据库或表才支持事务。
MySQL 事务主要用于处理操作量大,复杂度高的数据。
在 MySQL 中只有使用了 Innodb 数据库引擎的数据库或表才支持事务。
事务处理可以用来维护数据库的完整性,保证成批的 SQL 语句要么全部执行,要么全部不执行。
事务用来管理 insert,update,delete 语句
一般来说,事务是必须满足4个条件(ACID):原子性(Atomicity,或称不可分割性)、一致性(Consistency)、隔离性(Isolation,又称独立性)、持久性(Durability)。
Go语言MySQL事务应用包与函数:
1) import ("github.com/jmoiron/sqlx")
2) conn, err := Db.Begin() 开始事务
3) conn.Commit() 提交事务
4) conn.Rollback() 回滚事务
事务应用
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
type Student struct {
Id int `db:"id"`
Name string `db:"name"`
Sex string `db:"sex"`
Age int `db:"age"`
Course string `db:"course"`
}
var Db *sqlx.DB
func init() {
database, err := sqlx.Open("mysql", "root:root@tcp(127.0.0.1:3306)/oldboy")
if err != nil {
fmt.Println("open mysql failed,", err)
return
}
Db = database
}
func main() {
conn, err := Db.Begin()
if err != nil {
fmt.Println("begin failed :", err)
return
}
r, err := Db.Exec("insert into student(name, sex, age, course)values(?, ?, ?, ?)", "王五", "男", 18, "Golang")
if err != nil {
fmt.Println("exec failed, ", err)
conn.Rollback()
return
}
id, err := r.LastInsertId()
if err != nil {
fmt.Println("exec failed, ", err)
conn.Rollback()
return
}
fmt.Println("insert succ:", id)
r, err = Db.Exec("insert into student(name, sex, age, course)values(?, ?, ?, ?)", "赵六", "男", 18, "Linux、Python、Java")
if err != nil {
fmt.Println("exec failed, ", err)
conn.Rollback()
return
}
id, err = r.LastInsertId()
if err != nil {
fmt.Println("exec failed, ", err)
conn.Rollback()
return
}
fmt.Println("insert succ:", id)
conn.Commit()
}
查看MySQL:
mysql> select id,name,sex,age,course from student;
+----+--------+-----+------+-----------------------+
| id | name | sex | age | course |
+----+--------+-----+------+-----------------------+
| 2 | 王五 | 男 | 18 | Golang |
| 3 | 赵六 | 男 | 18 | Linux、Python、Java |
+----+--------+-----+------+-----------------------+
2 rows in set (0.00 sec)
老男孩教育Go开发课程2021全面升级(周末班), 试听即送价值69元纸质教材一本!
推荐阅读:
