Search code examples
sqlpostgresqlrestgopq

Error executing query with parameters in golang with postgres driver


I created a func that execute query on postgres database. I use the driver github.com/lib/pq

but if I run this:

_, err := repository.db.ExecContext(ctx, query, args...)

where query is

INSERT INTO fakeclients (uuid, name, last_name, birth_day, email, city, address, password, cellphone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)

and args is a slice with this values and its types

f1571b24-d88e-42b3-907e-13f46efabacc is a string
myname is a string
lastname is a string
2020-12-12 is a string
email is a string
Cali is a string
Calle is a string
mypassword is a string
12334455es is a string

the table was created with this properies

create table if not exists fakeclients (
    id                text,
    corporate_account boolean,
    name              text,
    last_name         text,
    cellphone         text,
    birth_day         text,
    email             text,
    password          text,
    city              text,
    address           text,
    primary key (id)
);

the result to execute this query is

pq: syntax error at or near ","

but if I insert the query with all values in the query string like this, it works

INSERT INTO fakeclients (uuid, name, last_name, birth_day, email, city, address, password, cellphone) VALUES ('f1571b24-d88e-42b3-907e-13f46efabacc is', 'myname', 'lastname', '2020-12-12', 'email', 'Cali', 'Calle', 'mypassword', '12334455es')

looks like the ExecContext method doesn't resolve the args as expected


Solution

  • Solved, for postgres the correct use of interpolation query is with $1, $2, $3...

    so the correct query would be

    INSERT INTO fakeclients (uuid, name, last_name, birth_day, email, city, address, password, cellphone) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)