sql - 使用 Postgres 时为 "Operator does not exist: integer =?"

标签 sql postgresql go pq

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

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 =? 看起来代码不理解 ? 只是一个占位符。我该如何解决这个问题?

最佳答案

PostgreSQL 原生使用编号占位符($1$2、...),而不是通常的位置问号。 documentation for the Go interface还在其示例中使用编号占位符:

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

Go 界面似乎没有像许多界面那样将问号转换为带编号的占位符,因此问号一直进入数据库并混淆了所有内容。

您应该能够切换到编号占位符而不是问号:

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

关于sql - 使用 Postgres 时为 "Operator does not exist: integer =?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58045701/

相关文章:

sql - 在其他计算机上使用路径

sql - 选择属性之间没有逗号?

xml - 在 golang 中收集所有具有给定名称的 xml 结构

c# - 确定文件中更改的字节的开始和结束范围

go - Go 在运行时获取函数参数

go - 从多个点扫描文件

sql - 设置连接超时也会终止服务器端的查询吗?

mysql - 使用自连接的 SQL 查询

php - 将sql查询的结果设置为php中if语句内的变量

node.js - 在 Nodejs-Express API 中 Sequelize body-parser 错误