英文:
Go SQL syntax error
问题
我正在尝试使用database/sql
将一行插入到Postgres表中。我运行的代码如下所示:
...
res, err := db.Exec("INSERT INTO image(name) VALUES(?);", fname)
if err != nil {
return err
}
...
fname
是一个字符串,类似于"image-name.png"
。image
表是通过以下语句创建的:
...
_, err := db.Exec("CREATE TABLE image (id SERIAL, name VARCHAR)")
...
在运行了CREATE TABLE
语句之后,我可以进入psql
并手动运行以下语句:
INSERT INTO image(name) VALUES('some-random-image.jpg');
这样就会将相应的行添加到image
表中。然而,上面的INSERT
Exec
调用始终报错,错误信息为pq: syntax error at or near ")"
。
有人能指出我在这里做错了什么吗?
另外,作为后续问题,有没有办法在go
中查看语句格式化的结果?我想到了类似于func Preview(template string, args...) string
的函数,用法如下:
Preview("INSERT INTO tbl(col) VALUES(?);", "test")
=> "INSERT INTO tbl(col) VALUES('test');"
请注意,我只会返回翻译好的部分,不会回答关于翻译的问题。
英文:
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');"
答案1
得分: 4
你需要在你的SQL中使用$1、$2等作为占位符值。占位符字符是依赖于数据库的,对于Postgres来说,它们是$X
。
英文:
You need to use $1, $2, ... as placeholder values in your SQL. The placeholder characters are DB dependent and for Postgres they are $X
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论