How to iterate simultaneously using sql result set in Golang?

The following () method is sequential, is there a way to iterate over a loop simultaneously?

I have a set of 200 thousand lines, which I repeat cyclically and execute the logic in each line and I want to break it.

+4
source share
1 answer

The sql.Rows that you return from your query cannot be used at the same time (I believe).

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

Here is an example (non-working, but close) on 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 {
        // be awesome
    }
}
func main() {
    ch := make(chan Row)
    // two handler go routines (current processors)
    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 {
            // do something with error
        } else {
            ch <- row
        }
    }
}
+4
source

Source: https://habr.com/ru/post/1615488/


All Articles