1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| package main
import ( "database/sql" "fmt" "log" "time"
_ "github.com/go-sql-driver/mysql" )
func main() { db, _ := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8")
stmt, _ := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?") res, _ := stmt.Exec("mebaron", "研发部门", time.Now())
id, _ := res.LastInsertId() fmt.Printf("id: %v\n", id)
stmt, _ = db.Prepare("delete from userinfo where uid=?") res, _ = stmt.Exec(id - 3) effect, _ := res.RowsAffected() fmt.Printf("delete effect: %v\n", effect)
stmt, _ = db.Prepare("update userinfo set username=? where uid=?") res, _ = stmt.Exec("baron", id)
effect, _ = res.RowsAffected() fmt.Printf("update effect: %v\n", effect)
rows, _ := db.Query("select * from userinfo")
for rows.Next() { var ( uid int username string departname string created string ) rows.Scan(&uid, &username, &departname, &created) fmt.Println(uid, username, departname, created) }
tx, _ := db.Begin() stmt, _ = tx.Prepare("INSERT userinfo SET username=?,departname=?,created=?") res, _ = stmt.Exec("tx", "测试部门", time.Now()) id, _ = res.LastInsertId() fmt.Printf("id: %v\n", id) res, _ = tx.Stmt(stmt).Exec("tx-baron", "测试1部门", time.Now()) id, _ = res.LastInsertId() fmt.Printf("id: %v\n", id)
stmt, _ = tx.Prepare("INSERT userdetail SET uid=?,intro=?,profile=?") stmt.Exec(id, "intro text", "profile text")
tx.Commit() }
|