“Operator does not exist: integer =?” when using Postgres

纵然是瞬间 提交于 2019-11-26 08:35:47

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/29887094/operator-does-not-exist-integer-when-using-postgres

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!