


How to use jackc/pgx with connection pooling, contexts, prepared statements, etc.
我仍然不是 golang 专家,仍在学习中。这也是我第一次接触postgresql
import "github.com/jackc/pgx/v5/pgxpool" const DB = "postgres://postgres:xxx@localhost:5432/mydb?pool_min_conns=1&pool_max_conns=5&pool_max_conn_idle_time=30s" dbpool, err := pgxpool.New(context.Background(), DB) if err != nil { log.Fatal("Unable to create connection pool: "+err.Error()) } defer dbpool.Close()
<强>1。如何从池中获取连接并使用准备好的语句,将 SQL 和 SQL 值作为两个单独的参数传递?
来自 PHP,之前从未使用过数据库池。
<强>2。如何确保从池中拉出连接时是“新鲜”的,并且不会继续之前未完成的事务(回滚/提交)?
<强>3。当您将连接释放回池时也是如此。如果上下文取消或者请求失败,会自动回滚吗?
<强>4。请求数据库时如何使用goroutine?是否可以在同一事务中进行并行选择查询,或者所有查询都必须是串行的?我想所有写入查询都必须是串行的?
正确答案
一般情况下你不会。池负责连接的管理(获取和释放)以及准备语句的管理(创建和缓存)。
但是,如果您想保持控制,则可以使用 Acquire
方法,或其任何相关方法。
类似地,如果您想手动创建并重用准备好的语句(例如,您需要在紧密循环中执行相同的查询,但您不想依赖池对准备好的语句的缓存),那么您可以使用获取的连接的 Conn
方法返回连接的 *pgx.Conn
表示,以及它有一个名为 Prepare
的方法。
池的获取方法返回可用连接。根据定义,正在使用的连接(即未释放的连接)不可用,并且不会由 Acquire 方法返回。
释放回池的连接所持有的资源,如果不空闲,将被销毁。。关于事务提交/回滚,它们都不会被自动调用, 文档明确指出:“必须对返回的事务调用提交或回滚才能最终确定事务块。”
该池可以安全地并发使用。但是 pgxpool.Conn
和 pgxpool.Tx
可以安全地并发使用。
示例:
Begin
不支持自动回滚或自动提交,您自己必须,如 文档,调用 Rollback
或 Commit
来“敲定交易区块”。
func f(ctx context.Context, pool *pgxpool.Pool) (err error) { tx, err := pool.Begin(ctx) if err != nil { return err } defer func() { if err != nil { tx.Rollback(ctx) } else { tx.Commit(ctx) } }() _, err := tx.Exec(ctx, "insert into users (email) values ($1)", "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="8cefcce9e1a2efe3e1">[email protected]</a>") if err != nil { return err } var id int row := tx.QueryRow(ctx, "select id from users where email = $1", "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="c5a685a0a8eba6aaa8">[email protected]</a>") if err := row.Scan(&id); err != nil { return err } // NOTE: the above is just an example, if you need the auto // generated id of an inserted record, please use the RETURNING // clause supported by PostgreSQL. return nil }
但是,您可以使用 BeginFunc
如果您希望 pgx 为您处理 Rollback
或 Commit
事务。
func f(ctx context.Context, pool *pgxpool.Pool) (err error) { return pool.BeginFunc(ctx, func(tx pgx.Tx) error { _, err := tx.Exec(ctx, "insert into users (email) values ($1)", "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="e98aa98c84c78a8684">[email protected]</a>") if err != nil { return err } var id int row := tx.QueryRow(ctx, "select id from users where email = $1", "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="492a092c24672a2624">[email protected]</a>") if err := row.Scan(&id); err != nil { return err } // NOTE: the above is just an example, if you need the auto // generated id of an inserted record, please use the RETURNING // clause supported by PostgreSQL. return nil }) }
The above is the detailed content of How to use jackc/pgx with connection pooling, contexts, prepared statements, etc.. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.
