package main import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "root:@tcp(localhost:3306)/ceshi") if err != nil { panic(err.Error()) } // 开始事物 返回一个事物指针 begin, err := db.Begin() if err != nil { panic(err.Error()) } // sql 语句 查询一条数据 sql := "select id, name, password, email from test where id = ? for update" row := t.QueryRow(sql, 2) var id int var name string var password string var email string err = row.Scan(&id, &name, &password, &email) if err != nil { t.Rollback() panic(err.Error()) } t.Commit() fmt.Println(id, name, password, email) // 查询多条数据 sql := "select id, name, password, email from test" rows, err := t.Query(sql) if err != nil { t.Rollback() panic(err.Error()) } users := make([]map[string]interface{}, 0) for rows.Next() { maps := make(map[string]interface{}, 4) var id int var name string var password string var email string err = rows.Scan(&id, &name, &password, &email) maps["id"] = id maps["name"] = name maps["password"] = password maps["email"] = email if err != nil { t.Rollback() panic(err.Error()) } users = append(users, maps) } t.Commit() for _, v := range users { fmt.Printf("id: %d, name: %s, password: %s, email: %s \n", v["id"], v["name"], v["password"], v["email"]) } }