Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 936
umezo Avatar asked Apr 27 '15 04:04

umezo


People also ask

What is the difference between int and Integer in PostgreSQL?

Integer. There are three kinds of integers in PostgreSQL: Small integer ( SMALLINT ) is 2-byte signed integer that has a range from -32,768 to 32,767. Integer ( INT ) is a 4-byte integer that has a range from -2,147,483,648 to 2,147,483,647.

How do I cast an expression in PostgreSQL?

PostgreSQL supports a CAST operator that is used to convert a value of one type to another. Syntax: CAST ( expression AS target_type ); Let's analyze the above syntax: First, specify an expression that can be a constant, a table column, an expression that evaluates to a value.

What is character varying in PostgreSQL?

PostgreSQL supports a character data type called VARCHAR. This data type is used to store characters of limited length. It is represented as varchar(n) in PostgreSQL, where n represents the limit of the length of the characters. If n is not specified it defaults to varchar which has unlimited length.


1 Answers

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)
like image 58
mu is too short Avatar answered Sep 21 '22 22:09

mu is too short