-2

I just begin to learn Go, and have a problem with returning ref vars from function

I have a function to get rows from a DB table:

func getData(query string, db *sql.DB) *sql.Rows {
    rows, err := db.Query(query)
    if err != nil {
        fmt.Println("SQL select error: ")
        log.Fatal(err)
    }
    defer rows.Close()

    return rows
}

now I try to get data from db

rows := getData("select * from all_obrash", db)
fmt.Println(rows)

I expect it just returns *sql.Rows but I get nothing

&{0xc00025e100 0x4cf270 0xc0002743c0 <nil> 0xc000248180 {{0 0} 0 0 0 0} true <nil> []}

When I call from main() it works just fine, but when I move code to func it stop get rows, I think I miss something here.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Vasilij Altunin
  • 754
  • 1
  • 5
  • 18
  • have you properly create db object? – Ali Zohrevand Dec 05 '18 at 06:27
  • 2
    What do you mean "I get nothing"? Your output is obviously something, _not_ nothing. – Jonathan Hall Dec 05 '18 at 07:02
  • [`sql.Rows`](https://golang.org/pkg/database/sql/#Rows) exposes an interface for iterating the result set. Printing the `sql.Rows` itself will get you nothing of value (the same as e.g. printing an `io.Reader` instead of actually reading from it). – Adrian Dec 05 '18 at 14:25

1 Answers1

3

defer rows.Close() gets executed when function returns

  func getData(query string, db *sql.DB) *sql.Rows {
    rows, err := db.Query(query)
    if err != nil {
        fmt.Println("SQL select error: ")
        log.Fatal(err)
    }
    defer rows.Close()

    return rows
}

That's why you're not able to read data

Prabesh P
  • 150
  • 4