1

I'm trying to get results from select query in a comma separated format (don't want results in a file). Following code works fine if I use stmt := fmt.Sprintf("SELECT * FROM table") but below code fails to reproduce any results because rows.Next() is empty. How to resolve this issue?

func (db *Dbq) Getresults() []interface{} {
    stmt := fmt.Sprintf("COPY (select * from table) TO STDOUT WITH CSV")

    var results []interface{}
    rows, err := db.conn.Query(db.context, stmt)
    for rows.Next() {
        values, err := rows.Values()
        if err != nil {
            log.Fatal(err)
        }
        results = append(results, values)
    }
    rows.Close()
    return results
}

I ran code with two different queries and debugged where it failed.

  • 1
    okey, I'll first try capturing stdout and see whether it works. thanks! – user1234845 Dec 05 '22 at 04:00
  • capture seems not working. may be because its ` rows, err := db.conn.Query(db.context, stmt)` never returned stdout. Let me try copy – user1234845 Dec 05 '22 at 04:49
  • 1
    Try this: https://go.dev/play/p/LwSgixTCdlc. From your question it's not clear how you want the csv decoded so the playground example just aggregates each csv record as a single string and adds that to a slice. If you need something more granular then perhaps you shouldn't use copy-to-csv at all and instead do a normal select-and-scan-into-structs. – mkopriva Dec 05 '22 at 06:25

0 Answers0