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

PHPz
Release: 2024-02-05 22:45:04
forward
745 people have browsed it

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=?")
Copy after login

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=?")
Copy after login


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)
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template