V
V
Vanes Ri_Lax2019-06-25 08:36:08
go
Vanes Ri_Lax, 2019-06-25 08:36:08

How to get response as array from database?

Good afternoon!
I'm trying to figure out how to work with a database in golang.
As a DBMS I have postgres I
wrote the following code:

func main() {
  db, err := sql.Open("postgres", config.PostgresqlConfig)
  if err != nil {
    log.Fatal(err)
  }
  defer db.Close()

  rows, err := db.Query("SELECT * FROM tablename")
  if err != nil {
    log.Fatal(err)
  }
  defer rows.Close()

  for rows.Next() {
    var a, b string

    err := rows.Scan(&a, &b)

    if err != nil {
      fmt.Println(err)
      continue
    }
    fmt.Println(a, b)
  }
}

I write the data to variables like this:
err := rows.Scan(&a, &b)
Everything works, but it's not very convenient for me, can I somehow get the answer in the form of an array or a slice?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Shitskov, 2019-06-25
@Zarom

It is most convenient to work with the database in golang using ORM. For example gorm .

A
Andrey Tsvetkov, 2019-06-25
@yellow79

Inside the loop, just insert your variables into the slice, and after the loop, process the resulting slice

P
Papa, 2019-06-25
Stifflera @PapaStifflera

With the driver "out of the box" you can not.
For postgri there is an alternative - go-pg ( https://github.com/go-pg/pg). It allows you to do what you want. And a whole bunch more.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question