Table of Contents
正确答案
示例:
Home Backend Development Golang How to use jackc/pgx with connection pooling, contexts, prepared statements, etc.

How to use jackc/pgx with connection pooling, contexts, prepared statements, etc.

Feb 08, 2024 pm 09:00 PM

如何将 jackc/pgx 与连接池、上下文、准备好的语句等一起使用

问题内容

我仍然不是 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()
Copy after login

<强>1。如何从池中获取连接并使用准备好的语句,将 SQL 和 SQL 值作为两个单独的参数传递?

来自 PHP,之前从未使用过数据库池。

<强>2。如何确保从池中拉出连接时是“新鲜”的,并且不会继续之前未完成的事务(回滚/提交)?

<强>3。当您将连接释放回池时也是如此。如果上下文取消或者请求失败,会自动回滚吗?

<强>4。请求数据库时如何使用goroutine?是否可以在同一事务中进行并行选择查询,或者所有查询都必须是串行的?我想所有写入查询都必须是串行的?


正确答案


一般情况下你不会。池负责连接的管理(获取和释放)以及准备语句的管理(创建和缓存)。

但是,如果您想保持控制,则可以使用 Acquire 方法,或其任何相关方法。

类似地,如果您想手动创建并重用准备好的语句(例如,您需要在紧密循环中执行相同的查询,但您不想依赖池对准备好的语句的缓存),那么您可以使用获取的连接的 Conn 方法返回连接的 *pgx.Conn 表示,以及它有一个名为 Prepare 的方法。

池的获取方法返回可用连接。根据定义,正在使用的连接(即未释放的连接)不可用,并且不会由 Acquire 方法返回。

释放回池的连接所持有的资源,如果不空闲,将被销毁。。关于事务提交/回滚,它们都不会被自动调用, 文档明确指出:“必须对返回的事务调用提交或回滚才能最终确定事务块。”

该池可以安全地并发使用。但是 pgxpool.Connpgxpool.Tx 可以安全地并发使用。

<小时/>

示例:

Begin 不支持自动回滚或自动提交,您自己必须,如 文档,调用 RollbackCommit 来“敲定交易区块”。

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&#160;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&#160;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
}
Copy after login

但是,您可以使用 BeginFunc如果您希望 pgx 为您处理 RollbackCommit 事务。

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&#160;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&#160;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
    })
}
Copy after login

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the go fmt command and why is it important? What is the go fmt command and why is it important? Mar 20, 2025 pm 04:21 PM

The article discusses the go fmt command in Go programming, which formats code to adhere to official style guidelines. It highlights the importance of go fmt for maintaining code consistency, readability, and reducing style debates. Best practices fo

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

See all articles