Updated on 2023-10-23 GMT+08:00

type Tx

The following table describes type Tx.

Method

Description

Return Value

(tx *Tx)Commit()

Commits a transaction.

error

(tx *Tx)Exec(query string, args ...interface{})

Performs an operation that does not return rows of data.

Result and error

(tx *Tx)ExecContext(ctx context.Context,

query string, args ...interface{})

Performs an operation that does not return rows of data in a specified context.

Result and error

(tx *Tx)Prepare(query string)

Creates a prepared statement for subsequent queries or executions. The returned statement is executed within a transaction and cannot be used when the transaction is committed or rolled back.

*Stmt and error

(tx *Tx)PrepareContext(ctx context.Context,

query string)

Creates a prepared statement for subsequent queries or executions. The returned statement is executed within a transaction and cannot be used when the transaction is committed or rolled back.

The specified context will be used in the preparation phase, not in the transaction execution phase. The statement returned by this method will be executed in the transaction context.

*Stmt and error

(tx *Tx)Query(query string, args ...interface{})

Executes a query that returns rows of data.

*Rows and error

(tx *Tx)QueryContext(ctx context.Context,

query string, args ...interface{})

Executes a query that returns rows of data in a specified context.

*Rows and error

(tx *Tx)QueryRow(query string, args ...interface{})

Executes a query that returns only one row of data.

*Row

(tx *Tx)QueryRowContext(ctx context.Context,

query string, args ...interface{})

Executes a query that returns only one row of data in a specified context.

*Row

(tx *Tx) Rollback()

Rolls back a transaction.

error

(tx *Tx)Stmt(stmt *Stmt)

Returns a transaction-specific prepared statement for an existing statement.

Example:

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)

Returns a transaction-specific prepared statement for an existing statement in a specified context.

*Stmt

Parameter Description

Parameter

Description

ctx

Specified context

query

Executed SQL statement

args

Parameter that needs to be bound to the executed SQL statement. Binding by location and binding by name are supported. For details, see the example in type DB.

stmt

Existing prepared statement, which is generally the prepared statement returned by the PREPARE statement