gpt4 book ai didi

go - 在一个事务中在 golang 中执行多个查询的惯用方式

转载 作者:IT王子 更新时间:2023-10-29 01:53:05 25 4
gpt4 key购买 nike

我目前正在努力(我的第 2 天)寻找执行多个查询的最佳方法,并且想知道您是否知道解决方案。

我有一个打开的 *sql.DB 连接,名为 myDb 并使用 go-sql-driver

func TruncateGalleryImport() error {

s := make([]string, 0)

s = append(s, "TRUNCATE TABLE add_map")
s = append(s, "TRUNCATE TABLE album")
s = append(s, "TRUNCATE TABLE album_permission")
s = append(s, "TRUNCATE TABLE album_view")
s = append(s, "TRUNCATE TABLE album_watch")
s = append(s, "TRUNCATE TABLE media")
s = append(s, "TRUNCATE TABLE media_user_view")
s = append(s, "TRUNCATE TABLE media_view")
s = append(s, "TRUNCATE TABLE media_watch")
s = append(s, "TRUNCATE TABLE private_map")
s = append(s, "TRUNCATE TABLE attachment")
s = append(s, "TRUNCATE TABLE attachment_data")

for _, q := range s {
_, err := myDb.Exec(q)
if err != nil {
return err
}
}

return nil
}

是否可以仅使用一个事务将上述所有查询一起提交?

干杯

最佳答案

使用事务,像这样(见代码中的注释):

func TruncateGalleryImport() error {
s := make([]string, 0)

s = append(s, "TRUNCATE TABLE add_map")
s = append(s, "TRUNCATE TABLE album")
s = append(s, "TRUNCATE TABLE album_permission")
s = append(s, "TRUNCATE TABLE album_view")
s = append(s, "TRUNCATE TABLE album_watch")
s = append(s, "TRUNCATE TABLE media")
s = append(s, "TRUNCATE TABLE media_user_view")
s = append(s, "TRUNCATE TABLE media_view")
s = append(s, "TRUNCATE TABLE media_watch")
s = append(s, "TRUNCATE TABLE private_map")
s = append(s, "TRUNCATE TABLE attachment")
s = append(s, "TRUNCATE TABLE attachment_data")

// Get new Transaction. See http://golang.org/pkg/database/sql/#DB.Begin
txn, err := myDb.Begin()

if err != nil {
return err
}

defer func() {
// Rollback the transaction after the function returns.
// If the transaction was already commited, this will do nothing.
_ = txn.Rollback()
}()

for _, q := range s {
// Execute the query in the transaction.
_, err := txn.Exec(q)

if err != nil {
return err
}
}

// Commit the transaction.
return txn.Commit()
}

关于go - 在一个事务中在 golang 中执行多个查询的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27741185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com