stmt, _ := app.DB.Prepare(query) de" />
A
A
Alex Plotnikov2018-10-28 00:36:21
go
Alex Plotnikov, 2018-10-28 00:36:21

Why doesn't select .. group by work properly in sql/pg golang?

I can't figure out why the query to the db is not working...

name := "filedname"
        var result []string

  query := `SELECT $1 FROM table GROUP BY $1;`

  stmt, _ := app.DB.Prepare(query)
  defer stmt.Close()

  rows, _ := stmt.Query(name)
  defer rows.Close()

  for rows.Next() {
    var res string
    rows.Scan(&res)
    result = append(result, res)
  }

error checking was intentionally removed here, if there are their checks, there are no errors.
The result is a slice of rows with one element [filedname] (field name) , although I'm expecting a slice of grouped values ​​of course.
Moreover, if I write hard query := `SELECT filedname FROM table GROUP BY filedname;` , then I get the expected slice.
Can someone tell me what's going on?)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eyeless_watcher, 2018-10-28
@TrueDevs

Bind variables can only be used to pass data, not to build the query itself. After substituting the values, the original query will look like `SELECT 'fieldname' from table group by 'fieldname'` (note the quotes around `fieldname`).
If you need to dynamically build the composition of the query (columns, group by, order by, etc.), there is no escape from its concatenation on the application side. The main thing is not to use user input in this concatenation (or, if it is still necessary, first check that the required column really exists and is allowed for such use).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question