如何在Golang中同时迭代SQL结果集?

huangapple go评论81阅读模式
英文:

How to concurrently iterate through an sql result set in Golang?

问题

next()方法是顺序执行的,有没有一种方法可以并发地迭代循环?

我有一个包含20万行的结果集,我正在顺序地遍历每一行,并对每一行进行逻辑操作,我想将其拆分。

英文:

The next() method is sequential, is there a way to concurrently iterate through the loop?

I have a result set of 200k rows that I am looping through sequentially and doing logic on each row and want to split it up.

答案1

得分: 9

你从查询中获得的sql.Rows不能同时使用(我相信)。

但你可以在goroutine中完成大部分繁重的工作。

这是一个示例(不可工作,但接近),在Play上:

package main

import "fmt"
import "sql"

type Row struct {
    x string
    y string
    z string
}

func processor(ch chan Row) {
    for row := range <-ch {
        // 做一些很棒的事情
    }
}
func main() {
    ch := make(chan Row)
    // 两个处理器goroutine
    go processor(ch)
    go processor(ch)
    rows := db.Query("select x,y,z from whatever")
    for rows.Next() {
        var row Row
        if err := rows.Scan(&row.x, &row.y, &row.z); err != nil {
            // 处理错误
        } else {
            ch <- row
        }
    }
}
英文:

The sql.Rows you get back from your query can't be used concurrently (I believe).

but you can do most of the heavy lifting in goroutines.

Here is an example (non-working, but close), on Play

package main

import &quot;fmt&quot;
import &quot;sql&quot;

type Row struct {
	x string
	y string
	z string
}

func processor(ch chan Row) {
	for row := range &lt;-ch {
		// be awesome
	}
}
func main() {
	ch := make(chan Row)
	// two handler go routines (current processors)
	go processor(ch)
	go processor(ch)
	rows := db.Query(&quot;select x,y,z from whatever&quot;)
	for rows.Next() {
		var row Row
		if err := rows.Scan(&amp;row.x, &amp;row.y, &amp;row.z); err != nil {
			// do something with error
		} else {
			ch &lt;- row
		}
	}
}

huangapple
  • 本文由 发表于 2015年11月12日 06:59:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/33661442.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定