Golang + Postgres WHERE clause with hex value
I created a simple sql database with BYTEA field,
create table testhex (testhex bytea);
insert into testhex (testhex) values ('\x123456');
and then I tried to request it from Go.
package main
import (
"database/sql"
_ "github.com/lib/pq"
)
func main(){
var err error
db, err := sql.Open("postgres", "dbname=testhex sslmode=disable")
if err != nil {
panic(err)
}
var result string
err = db.QueryRow("select testhex from testhex where testhex = $1", `\x123456`).Scan(&result)
if err != nil {
panic(err)
}
}
It doesn't find the string. What am I doing wrong?
source to share
When running the following query:
insert into testhex (testhex) values ('\x123456');
You have inserted a 3 byte sequence [0x12 0x34 0x56]
into the table. For a database query that you are doing with QueryRow
, however, you are looking for an 8-character letter string \x123456
so you don't get a match in the result.
When you use positional arguments with QueryRow
, specifying a database adapter converts them to a form that the database understands (either by submitting them to the database as bound parameters, or by substituting them in the query with appropriate escaping). Thus, passing in an already escaped value, you will run into such a problem.
Instead, try passing []byte{0x12, 0x34, 0x56}
positional as the argument, which should match what is in the database.
source to share