我仍然不是 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 }) }
以上是如何将 jackc/pgx 与连接池、上下文、准备好的语句等一起使用的详细内容。更多信息请关注PHP中文网其他相关文章!

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Go的错误接口定义为typeerrorinterface{Error()string},允许任何实现Error()方法的类型被视为错误。使用步骤如下:1.基本检查和记录错误,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。2.创建自定义错误类型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。3.使用错误包装(自Go1.13起)来添加上下文而不丢失原始错误信息,

对效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,EmparterRorwatchers,InsterTimeouts,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErstopassErrorsErtopassErrorsErrorsFromGoroutInestotheStothemainfunction.2)

在Go语言中,接口的实现是通过隐式的方式进行的。1)隐式实现:类型只要包含接口定义的所有方法,就自动满足该接口。2)空接口:interface{}类型所有类型都实现,适度使用可避免类型安全问题。3)接口隔离:设计小而专注的接口,提高代码的可维护性和重用性。4)测试:接口有助于通过模拟依赖进行单元测试。5)错误处理:通过接口可以统一处理错误。

go'sinterfacesareimpliclyimplysed,与Javaandc#wheRequireexplitiCimplation.1)Ingo,AnyTypewithTheRequiredMethodSautSautsautautapitymethodimimplementalyimimplementsaninternItherninternionterface,callingingSimplicity andficityity.2)

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

开发者应遵循以下最佳实践:1.谨慎管理goroutines以防止资源泄漏;2.使用通道进行同步,但避免过度使用;3.在并发程序中显式处理错误;4.了解GOMAXPROCS以优化性能。这些实践对于高效和稳健的软件开发至关重要,因为它们确保了资源的有效管理、同步的正确实现、错误的适当处理以及性能的优化,从而提升软件的效率和可维护性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

WebStorm Mac版
好用的JavaScript开发工具