4

I'm trying to insert a row into a Postgres table using database/sql. The code I'm running looks like

...
res, err := db.Exec("INSERT INTO image(name) VALUES(?);", fname)
if err != nil {
    return err
}
...

fname is a string. Something like "image-name.png". The image table was created by the statement

...
_, err := db.Exec("CREATE TABLE image (id SERIAL, name VARCHAR)")
...

After running that CREATE TABLE statement, I'm able to hop into psql and manually run

INSERT INTO image(name) VALUES('some-random-image.jpg');

with the appropriate row being added to the image table. However, the INSERT Exec call above consistently errors with pq: syntax error at or near ")".

Can anyone point out what I'm doing wrong here?

Also, as a follow-up, is there any way to see the result of statement formatting in go? I'm thinking of something like func Preview (template string, args...) string such that

Preview("INSERT INTO tbl(col) VALUES(?);", "test")
   => "INSERT INTO tbl(col) VALUES('test');"
0

1 Answer 1

4

You need to use $1, $2, ... as placeholder values in your SQL. The placeholder characters are DB dependent and for Postgres they are $X.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.