登录
首页 >  Golang >  Go问答

避免并发 Goroutine 中的数据库连接关闭

来源:stackoverflow

时间:2024-03-21 12:54:33 214浏览 收藏

为了在并发 Goroutine 中避免数据库连接关闭,在 `updaterowforsomereason` 函数中执行查询时,出现了错误,提示“数据库已关闭”。解决方案是优化 SQL 结构,将两层嵌套语句合并为一个嵌套查询,从而在数据库中直接完成所有操作,避免加载结果集到程序内存中并逐一执行更新语句。

问题内容

我有一个大约有 2000000 行的章节表,我想根据某些特定条件更新每一行:

func main(){
    rows, err := db.query("select id from chapters where title = 'custom_type'")
    if err != nil {
       panic(err)
    }

    for rows.next() {
        var id int
        _ = rows.scan(&id)
        fmt.println(id)
        go updaterowforsomereason(id)
    }
}

func updaterowforsomereason(id int) {
    row, err := db.query(fmt.sprintf("select id from chapters where parent_id = %v", id))  
    if err != nil {
        panic(err)  <----- // here is the panic occurs 
    }
    for rows.next() {
       // ignore update code for simplify
    }
}

updaterowforsomereason 内,我为每一行执行更新语句。

它会在几秒钟内起作用,之后将打印错误:

323005 
323057 
323125 
323244 
323282 
323342 
323459 
323498 
323556 
323618 
323693 
325343 
325424 
325468 
325624 
325816 
326001 
326045 
326082 
326226 
326297 
panic: sql: database is closed

解决方案


这似乎不是一个 go 问题,更多的是如何在代码中优化 sql 结构的问题。您正在通过对 2,000,000 行执行查询来获取结果集:

rows, err := db.query("select id from chapters where title = 'custom_type'")

然后对此结果集中的每行执行另一个查询:

row, err := db.query(fmt.sprintf("select id from chapters where parent_id = %v", id))

然后为每一个执行更多代码,显然是一个接一个:

for rows.next() {
   // ignore update code for simplify
}

这实际上是两层语句嵌套,这是将所有这些结果加载到程序内存中然后执行独立 update 语句的非常低效的方式:

select
     +---->select
                +---->update

相反,您可以在数据库本身中完成所有工作,这会更加高效。您没有显示 update 语句是什么,但这是关键部分。假设您要设置 publish 标志。你可以这样做:

update chapters
    set publish=true
    where parent_id in
        (select id from chapters
         where title='custom_type')
    returning id;

通过使用嵌套查询,您可以将三个独立查询的全部合并为一个查询。数据库拥有优化操作和构建最有效的查询计划所需的所有信息,并且您仅执行单个 db.query 操作。 returning 子句允许您检索在操作中最终更新的 id 列表。所以代码就很简单:

func main(){
    rows, err := db.Query("UPDATE chapters SET publish=true WHERE parent_id in" +
                          "(SELECT id FROM chapters WHERE title='custom_type')" +
                          "RETURNING id;")
    if err != nil {
       panic(err)
    }

    for rows.Next() {
        var id int
        _ = rows.Scan(&id)
        fmt.Println(id)
    }
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>