Running prepared statements within a transaction
A statement can be prepared by calling the *sql.Tx.Prepare or *sql.Tx.PrepareContext method of the transaction struct. The prepared statement returned by these two will be associated with that transaction only. That is, you cannot prepare a statement using one transaction and use that statement for another transaction.
How to do it...
There are two ways you can use prepared statements in a transaction.
The first is using a statement prepared by *DB:
- Prepare the statement using
DB.PrepareorDB.PrepareContext. - Get a transaction-specific copy of the transaction:
txStmt := tx.Stmt(stmt)
- Run the operations using the new statement.
- The second is using a statement prepared by
*Tx: - Prepare the statement using
Tx.PrepareorTx.PrepareContext. - Run the operations using this statement.