在使用Postgres时出现了”Operator does not exist: integer =?”的错误。

huangapple go评论102阅读模式
英文:

"Operator does not exist: integer =?" when using Postgres

问题

我有一个简单的SQL查询,使用go的database/sql包提供的QueryRow方法调用。

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)
}

然而,我得到了错误信息 pq: operator does not exist: integer =?。看起来代码无法理解 ? 只是一个占位符。我该如何修复这个问题?

英文:

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

得分: 19

PostgreSQL使用编号占位符($1$2,...)而不是通常的位置问号。Go接口的文档在示例中也使用了编号占位符:

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

看起来Go接口没有像许多其他接口那样将问号转换为编号占位符,所以问号一直传递到数据库并导致混淆。

你可以使用编号占位符而不是问号:

 row := db.QueryRow(
    "SELECT name FROM users WHERE id = $1", id)
英文:

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)

huangapple
  • 本文由 发表于 2015年4月27日 12:14:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/29887094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定