9

I have a simple SQL query called within the QueryRow method provided by go's database/sql package.

import (
  "github.com/codegangsta/martini"
  "github.com/martini-contrib/render"
  "net/http"
  "database/sql"
  "fmt"
  _ "github.com/lib/pq")
)

type User struct {
  Name string
}

func Show(db *sql.DB, params martini.Params) {
  id := params["id"]
  row := db.QueryRow(
    "SELECT name FROM users WHERE id=?", id)
  u := User{}
  err := row.Scan(&u.Name)
  fmt.Println(err)
}

However, I'm getting the error pq: operator does not exist: integer =? It looks like the code doesn't understand that the ? is just a placeholder. How can I fix this?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
umezo
  • 1,519
  • 1
  • 19
  • 33
  • 3
    The reason you get that particular error is that `=?` would be a valid PostgreSQL operator name. Use `id = ?`. But as mu says, it's likely also that Go doesn't use `?` as a placeholder. – Craig Ringer Apr 27 '15 at 04:31

1 Answers1

19

PostgreSQL works with numbered placeholders ($1, $2, ...) natively rather than the usual positional question marks. The documentation for the Go interface also uses numbered placeholders in its examples:

rows, err := db.Query("SELECT name FROM users WHERE age = $1", age)

Seems that the Go interface isn't translating the question marks to numbered placeholders the way many interfaces do so the question mark is getting all the way to the database and confusing everything.

You should be able to switch to numbered placeholders instead of question marks:

 row := db.QueryRow(
    "SELECT name FROM users WHERE id = $1", id)
mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • 2
    got it, thanks. I didn't realize this, as the go docs for database/sql use the question mark. http://golang.org/pkg/database/sql/#NullString – umezo Apr 27 '15 at 04:39
  • 3
    umezo: I'm sure you've already been there, but it's worth reading the documentation for your postgresql driver as well (and not only for the dollar issue): http://godoc.org/github.com/lib/pq – tomasz Apr 27 '15 at 09:59