Home >Backend Development >Golang >Will context be used by default in the entire sql transaction?

Will context be used by default in the entire sql transaction?

PHPz
PHPzforward
2024-02-05 22:45:04782browse

Will context be used by default in the entire sql transaction?

Question content

I was wondering if you use the context to start the transaction if the entire transaction will be "listening" here?

tx, _ := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
stmt, _ := tx.Prepare("SELECT id, timeout, lang FROM client WHERE id=?")

Or do you explicitly apply the context to each query?

tx, _ := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
stmt, _ := tx.PrepareContext(ctx, "SELECT id, timeout, lang FROM client WHERE id=?")

Correct answer


No. Prepare and other context-free methods, please use context.Background.

From Tx.Prepare documentation...

View Source code, it's just a simple wrapper.

func (tx *Tx) Prepare(query string) (*Stmt, error) {
    return tx.PrepareContext(context.Background(), query)
}

While Tx does store context from db.BeginTx, this is only used for transactions. It won't use it for queries because shared context would cause confusion and limit .

The above is the detailed content of Will context be used by default in the entire sql transaction?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete