带有间隔参数的Go postgres准备语句不起作用
Go postgres prepared statement with interval parameter not working
我正在尝试使用 Go 的 pq 库将以下内容简单地插入到 postgres 数据库中(我正在阅读 Let's Go 这本书,但使用的是 Postgres 而不是 mySQL):
title := "O snail"
content := "O snail\nClimb Mount Fuji,\nBut slowly, slowly!\n\n - Kobayashi"
expires := "7"
stmt := `INSERT INTO snippets (title, content, created, expires)
VALUES(, , current_timestamp, current_timestamp + interval ' days')`
_, err := m.DB.Exec(stmt, title, content, expires)
但这会引发错误:
handlers.go:56: pq: got 3 parameters but the statement requires 2
事实上,如果我只是从最后一行删除 expires
,并传入 2 个参数,它就可以工作,并且间隔值被视为“3 天”。
这有什么意义?为什么 $
被忽略了?我认为这是由于一些用单引号转义的东西,所以我尝试了'$3 days'
,但它给出了一个错误pq: syntax error at or near "\"
。如果我尝试转义单引号 \' days\'
,我也会收到错误消息。有什么建议吗?
您可以将 interval '1 day'
乘以绑定参数,以获得您想要的正确间隔。
stmt := `INSERT INTO snippets (title, content, created, expires)
VALUES(, , current_timestamp, current_timestamp + interval '1 day' * )`
您也可以将参数转换为 interval
并将完整的区间字符串作为查询参数传递:
expires := "7 days"
stmt := `INSERT INTO snippets (title, content, created, expires)
VALUES(, , current_timestamp, current_timestamp + ::interval)`
_, err := m.DB.Exec(stmt, title, content, expires)
这也使您可以更好地控制如何确定 expire
的值,例如使用 fmt.Sprintf
或字符串连接,以防您还想将时间单位作为外部提供的参数。
我正在尝试使用 Go 的 pq 库将以下内容简单地插入到 postgres 数据库中(我正在阅读 Let's Go 这本书,但使用的是 Postgres 而不是 mySQL):
title := "O snail"
content := "O snail\nClimb Mount Fuji,\nBut slowly, slowly!\n\n - Kobayashi"
expires := "7"
stmt := `INSERT INTO snippets (title, content, created, expires)
VALUES(, , current_timestamp, current_timestamp + interval ' days')`
_, err := m.DB.Exec(stmt, title, content, expires)
但这会引发错误:
handlers.go:56: pq: got 3 parameters but the statement requires 2
事实上,如果我只是从最后一行删除 expires
,并传入 2 个参数,它就可以工作,并且间隔值被视为“3 天”。
这有什么意义?为什么 $
被忽略了?我认为这是由于一些用单引号转义的东西,所以我尝试了'$3 days'
,但它给出了一个错误pq: syntax error at or near "\"
。如果我尝试转义单引号 \' days\'
,我也会收到错误消息。有什么建议吗?
您可以将 interval '1 day'
乘以绑定参数,以获得您想要的正确间隔。
stmt := `INSERT INTO snippets (title, content, created, expires)
VALUES(, , current_timestamp, current_timestamp + interval '1 day' * )`
您也可以将参数转换为 interval
并将完整的区间字符串作为查询参数传递:
expires := "7 days"
stmt := `INSERT INTO snippets (title, content, created, expires)
VALUES(, , current_timestamp, current_timestamp + ::interval)`
_, err := m.DB.Exec(stmt, title, content, expires)
这也使您可以更好地控制如何确定 expire
的值,例如使用 fmt.Sprintf
或字符串连接,以防您还想将时间单位作为外部提供的参数。