GO語言"database/sql"包中"Tx.Prepare"類型的用法及代碼示例。
用法:
func(tx *Tx) Prepare(query string)(*Stmt, error)
Prepare 創建一個準備好的語句以在事務中使用。
返回的語句在事務中運行,並在事務提交或回滾時關閉。
要在此事務上使用現有的準備好的語句,請參閱 Tx.Stmt。
Prepare 在內部使用 context.Background;要指定上下文,請使用PrepareContext
例子:
package main
import (
"context"
"database/sql"
"log"
)
var (
ctx context.Context
db *sql.DB
)
func main() {
projects := []struct {
mascot string
release int
}{
{"tux", 1991},
{"duke", 1996},
{"gopher", 2009},
{"moby dock", 2013},
}
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
defer tx.Rollback() // The rollback will be ignored if the tx has been committed later in the function.
stmt, err := tx.Prepare("INSERT INTO projects(id, mascot, release, category) VALUES( ?, ?, ?, ? )")
if err != nil {
log.Fatal(err)
}
defer stmt.Close() // Prepared statements take up server resources and should be closed after use.
for id, project := range projects {
if _, err := stmt.Exec(id+1, project.mascot, project.release, "open source"); err != nil {
log.Fatal(err)
}
}
if err := tx.Commit(); err != nil {
log.Fatal(err)
}
}
相關用法
- GO Tx.ExecContext用法及代碼示例
- GO Tx.Rollback用法及代碼示例
- GO Time.Sub用法及代碼示例
- GO TrailingZeros8用法及代碼示例
- GO Template用法及代碼示例
- GO Time.Equal用法及代碼示例
- GO ToTitle用法及代碼示例
- GO Time.After用法及代碼示例
- GO Title用法及代碼示例
- GO TrimRight用法及代碼示例
- GO ToLowerSpecial用法及代碼示例
- GO TempFile用法及代碼示例
- GO Time.Format用法及代碼示例
- GO ToUpper用法及代碼示例
- GO Trunc用法及代碼示例
- GO TrailingZeros32用法及代碼示例
- GO To用法及代碼示例
- GO Time.AppendFormat用法及代碼示例
- GO Time.AddDate用法及代碼示例
- GO Tan用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Tx.Prepare。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。