


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!

In Go, using mutexes and locks is the key to ensuring thread safety. 1) Use sync.Mutex for mutually exclusive access, 2) Use sync.RWMutex for read and write operations, 3) Use atomic operations for performance optimization. Mastering these tools and their usage skills is essential to writing efficient and reliable concurrent programs.

How to optimize the performance of concurrent Go code? Use Go's built-in tools such as getest, gobench, and pprof for benchmarking and performance analysis. 1) Use the testing package to write benchmarks to evaluate the execution speed of concurrent functions. 2) Use the pprof tool to perform performance analysis and identify bottlenecks in the program. 3) Adjust the garbage collection settings to reduce its impact on performance. 4) Optimize channel operation and limit the number of goroutines to improve efficiency. Through continuous benchmarking and performance analysis, the performance of concurrent Go code can be effectively improved.

The common pitfalls of error handling in concurrent Go programs include: 1. Ensure error propagation, 2. Processing timeout, 3. Aggregation errors, 4. Use context management, 5. Error wrapping, 6. Logging, 7. Testing. These strategies help to effectively handle errors in concurrent environments.

ImplicitinterfaceimplementationinGoembodiesducktypingbyallowingtypestosatisfyinterfaceswithoutexplicitdeclaration.1)Itpromotesflexibilityandmodularitybyfocusingonbehavior.2)Challengesincludeupdatingmethodsignaturesandtrackingimplementations.3)Toolsli

In Go programming, ways to effectively manage errors include: 1) using error values instead of exceptions, 2) using error wrapping techniques, 3) defining custom error types, 4) reusing error values for performance, 5) using panic and recovery with caution, 6) ensuring that error messages are clear and consistent, 7) recording error handling strategies, 8) treating errors as first-class citizens, 9) using error channels to handle asynchronous errors. These practices and patterns help write more robust, maintainable and efficient code.

Implementing concurrency in Go can be achieved by using goroutines and channels. 1) Use goroutines to perform tasks in parallel, such as enjoying music and observing friends at the same time in the example. 2) Securely transfer data between goroutines through channels, such as producer and consumer models. 3) Avoid excessive use of goroutines and deadlocks, and design the system reasonably to optimize concurrent programs.

Gooffersmultipleapproachesforbuildingconcurrentdatastructures,includingmutexes,channels,andatomicoperations.1)Mutexesprovidesimplethreadsafetybutcancauseperformancebottlenecks.2)Channelsofferscalabilitybutmayblockiffullorempty.3)Atomicoperationsareef

Go'serrorhandlingisexplicit,treatingerrorsasreturnedvaluesratherthanexceptions,unlikePythonandJava.1)Go'sapproachensureserrorawarenessbutcanleadtoverbosecode.2)PythonandJavauseexceptionsforcleanercodebutmaymisserrors.3)Go'smethodpromotesrobustnessand


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

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