type Tx
type Tx接口定义了一系列方法,用于管理数据库事务,常用方法如表1所示。
| 方法 | 描述 | 返回值类型 |
| (tx *Tx)Commit() | 提交事务。 | error |
| (tx *Tx)Exec(query string, args ...interface{}) | 执行不返回数据行的操作。 | Result, error |
| (tx *Tx)ExecContext(ctx context.Context, query string, args ...interface{}) | 在给定上下文中执行不返回数据行的操作。 | Result, error |
| (tx *Tx)Prepare(query string) | 为后续的SQL语句创建预处理语句。返回的语句将在事务中执行,事务提交或回滚后不可继续使用。 | *Stmt, error |
| (tx *Tx)PrepareContext(ctx context.Context, query string) | 在给定上下文中为后续的SQL语句创建预处理语句。返回的语句将在事务中执行,事务提交或回滚后不可继续使用。 | *Stmt, error |
| (tx *Tx)Query(query string, args ...interface{}) | 执行查询并返回多行数据。 | *Rows, error |
| (tx *Tx)QueryContext(ctx context.Context, query string, args ...interface{}) | 在给定上下文中执行查询并返回多行数据。 | *Rows, error |
| (tx *Tx)QueryRow(query string, args ...interface{}) | 执行查询并返回单行数据。 | *Row |
| (tx *Tx)QueryRowContext(ctx context.Context, query string, args ...interface{}) | 在给定上下文中执行查询并返回单行数据。 | *Row |
| (tx *Tx)Rollback() | 事务回滚。 | error |
| (tx *Tx)Stmt(stmt *Stmt) | 将已有的预处理语句绑定到当前事务,返回事务专用的预处理语句。 示例: str, err := db.Prepare("INSERT INTO t1 VALUES(:1, :2)")
tx, err := db.Begin()
res, err := tx.Stmt(str).Exec(1, "aaa") | *Stmt |
| (tx *Tx)StmtContext(ctx context.Context, stmt *Stmt) | 在给定上下文中,将已有的预处理语句绑定到当前事务,返回事务专用的预处理语句。 | *Stmt |
参数说明
| 参数 | 参数说明 |
| ctx | 表示给定的上下文。 |
| query | 表示待执行的SQL语句。 |
| args | 表示待执行SQL语句需要绑定的参数。支持按位置绑定和按名称绑定,参见示例。 |
| stmt | 已有的预处理语句(由Prepare或PrepareContext方法返回)。 |
- Query类方法Query()、QueryContext()、QueryRow()、QueryRowContext()用于执行返回数据行的语句。
- Exec类方法Exec()、ExecContext()用于执行不返回数据行的语句。
- 若使用Query类方法执行DML操作,则可能出现执行结果与预期不符的情况。因此不建议使用Query类方法执行增、删、改操作。