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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
| package main
import ( "database/sql" "fmt" "log" "strings"
_ "github.com/go-sql-driver/mysql" )
func mysql_open() (*sql.DB, error) { db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/mysql") if err != nil { log.Fatal(err) }
return db, err }
type tt struct { id int c int d int field string }
func queryAll(db *sql.DB) []*tt { var ret []*tt rows, err := db.Query("select id, c, d, field from tt where 1 = ?", 1) defer rows.Close() if err != nil { log.Fatal(err) }
fmt.Println("id\tc\td\tfield") for rows.Next() { data := &tt{} err = rows.Scan(&data.id, &data.c, &data.d, &data.field) if err != nil { log.Fatal(err) } ret = append(ret, data) fmt.Println(data.id, "\t", data.c, "\t", data.d, "\t", data.field) }
err = rows.Err() if err != nil { log.Fatal(err) }
return ret }
func querySingle(db *sql.DB) *tt { var data tt err := db.QueryRow("select id, c, d, field from tt where id = ?", 1).Scan(&data.id, &data.c, &data.d, &data.field) if err != nil { log.Fatal(err) } fmt.Println() fmt.Println("id\tc\td\tfield") fmt.Println(data.id, "\t", data.c, "\t", data.d, "\t", data.field) return &data }
func modifybyTx(db *sql.DB, data []*tt) { tx, err := db.Begin() if err != nil { fmt.Println("begin tx err!") log.Fatal(err) }
defer func() { if err == nil { _ = tx.Commit() } else { _ = tx.Rollback() } }()
param := make([]interface{}, 0) for _, row := range data { param = append(param, row.id) }
sql := strings.Builder{} sql.WriteString(fmt.Sprintf("update tt set field = unix_timestamp(NOW()) where id in (?%s)", strings.Repeat(", ?", len(data)-1)))
_, err = tx.Exec(sql.String(), param...) if err != nil { log.Fatal(err) } }
func main() { db, err := mysql_open() if err != nil { fmt.Println("open mysql error!") return }
var data []*tt data = queryAll(db) fmt.Println("-------------------------") querySingle(db) fmt.Println("-------------------------") modifybyTx(db, data) queryAll(db) fmt.Println("-------------------------")
defer func() { db.Close() }() }
|