Go SQL 语法错误

huangapple go评论82阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年7月3日 05:05:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/31194630.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定