5

I have a simple select statement:

Select * FROM X where X.name in ("bob", "joe") and X.phone='123'

That works fine in postgres,

In my Go code I have the following code:

var phone string = "123"
var names []string = []string{"bob", "joe"}
sqlStatement := `Select * FROM X where X.name in ($1) and X.phone=$2`
rows, sqlerr := db.Query(sqlStatement, names, phone)

but for some reason I error out from that sql.

unsupported Scan, storing driver.Value type into type *string

how can i use my names array in side the sqlstatement?

note: if i do a fmt.printf and paste the sql statement into postgres, i do get data back + if i take out the $1, and manually input the strings

Nate
  • 1,630
  • 2
  • 24
  • 41
  • Use `X.name = ANY ($1)` with [`lib/pq` array types](https://godoc.org/github.com/lib/pq#StringArray). – mkopriva Nov 06 '18 at 19:16
  • 1
    Possible duplicate of [Go and IN clause in Postgres](https://stackoverflow.com/questions/38036752/go-and-in-clause-in-postgres) – Jonathan Hall Nov 06 '18 at 19:46

2 Answers2

6

Copying and pasting fragments from some working Go PostgreSQL code:

import (
    "database/sql"
    "github.com/lib/pq"
)

    query := `
            . . .
            WHERE code = ANY($1)
           . . .

        `

    codes := []string{"JFK", "LGA", "EWR"}
    rows, err := db.Query(query, pq.Array(codes))
peterSO
  • 158,998
  • 31
  • 281
  • 276
0

I solved this using http://jmoiron.github.io/sqlx/#inQueries

var phone string = "123"
var names []string = []string{"bob", "joe"}
sqlStatement := `Select * FROM X where X.name in (?) and X.phone=?`
sqlStatement, args, err := sqlx.In(sqlStatement, names, phone)
sqlStatement = db.Rebind(sqlStatement)
        rows, sqlerr := db.Queryx(sqlStatement, args...)

this now returns correctly.

another way to solve this was to use fmt.Sprintf() and converting the ? to %s

Nate
  • 1,630
  • 2
  • 24
  • 41