我試圖通過使用 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($1, $2, current_timestamp, current_timestamp interval '$3 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 "\"。如果我嘗試轉義單引號,我也會收到錯誤訊息\'$3 days\'。有什么建議?
uj5u.com熱心網友回復:
您還可以將引數轉換為interval并將完整的間隔字串作為查詢引數傳遞:
expires := "7 days"
stmt := `INSERT INTO snippets (title, content, created, expires)
VALUES($1, $2, current_timestamp, current_timestamp $3::interval)`
_, err := m.DB.Exec(stmt, title, content, expires)
這也使您可以更好地控制如何確定 的值expire,例如與fmt.Sprintf或字串連接,以防您還希望將時間單位作為外部提供的引數。
uj5u.com熱心網友回復:
您可以乘以interval '1 day'一個系結引數,以獲得您想要的正確間隔。
stmt := `INSERT INTO snippets (title, content, created, expires)
VALUES($1, $2, current_timestamp, current_timestamp interval '1 day' * $3)`
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/439838.html
標籤:PostgreSQL 走
上一篇:如何解決模板:模式不匹配檔案
