“运算符不存在:integer =?”当与Golang一起使用Postgres时 [英] "Operator does not exist: integer =?" when using Postgres with Golang

查看:183
本文介绍了“运算符不存在:integer =?”当与Golang一起使用Postgres时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在go的database / sql包提供的QueryRow方法中调用了一个简单的SQL查询。

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


类型用户结构{
名称字符串
}

func显示(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:运算符不存在:integer =?它看起来像代码不明白只是一个占位符。如何解决这个问题?

解决方案

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)


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?

解决方案

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)

这篇关于“运算符不存在:integer =?”当与Golang一起使用Postgres时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆