GO語言"database/sql"包中"DB.BeginTx"類型的用法及代碼示例。
用法:
func(db *DB) BeginTx(ctx context.Context, opts *TxOptions)(*Tx, error)
BeginTx 開始一個事務。
在事務提交或回滾之前使用提供的上下文。如果上下文被取消,則 sql 包將回滾事務。如果取消提供給BeginTx 的上下文,Tx.Commit 將返回錯誤。
提供的TxOptions 是可選的,如果應該使用默認值,則可能為零。如果使用驅動程序不支持的非默認隔離級別,則會返回錯誤。
例子:
package main
import (
"context"
"database/sql"
"log"
)
var (
ctx context.Context
db *sql.DB
)
func main() {
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil {
log.Fatal(err)
}
id := 37
_, execErr := tx.Exec(`UPDATE users SET status = ? WHERE id = ?`, "paid", id)
if execErr != nil {
_ = tx.Rollback()
log.Fatal(execErr)
}
if err := tx.Commit(); err != nil {
log.Fatal(err)
}
}
相關用法
- GO DB.QueryRowContext用法及代碼示例
- GO DB.ExecContext用法及代碼示例
- GO DB.QueryContext用法及代碼示例
- GO DB.Prepare用法及代碼示例
- GO DB.Query用法及代碼示例
- GO DB.PingContext用法及代碼示例
- GO DecodeLastRuneInString用法及代碼示例
- GO DumpResponse用法及代碼示例
- GO Date用法及代碼示例
- GO Dial用法及代碼示例
- GO Decoder.Token用法及代碼示例
- GO Decoder.Decode用法及代碼示例
- GO DumpRequest用法及代碼示例
- GO Drawer用法及代碼示例
- GO Duration.Hours用法及代碼示例
- GO Duration.Round用法及代碼示例
- GO DecodeRuneInString用法及代碼示例
- GO DumpRequestOut用法及代碼示例
- GO DecodeRune用法及代碼示例
- GO Duration用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 DB.BeginTx。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。