2 回答

TA貢獻1779條經驗 獲得超6個贊
從您收到的錯誤中:
expected 2 arguments, got 3
我懷疑$3
在 SQL 引號內的查詢中不會被解釋為參數。另外據我所知,這不是在 postgres 中使用參數間隔的正確方法。正確的方法是寫interval '1 day' * $1
所以我認為如果您將代碼更改為:
stmt := `INSERT INTO widgets (title, content, created, expires) VALUES($1, $2, NOW(), NOW() + INTERVAL '1 day' * $3) RETURNING id;`
它會起作用的。但請確保將expires
參數更改為 int 類型。

TA貢獻1890條經驗 獲得超9個贊
'$3 day' 您不能將查詢參數作為字符串文字的一部分傳遞。
嘗試將所有INTERVAL '$3 day'部分替換為參數。像這個。
func (m *WidgetModel) Insert(title, content, expires string) (int, error) {
stmt := `
INSERT INTO widgets (title, content, created, expires)
VALUES ($1, $2, NOW(), NOW() + $3)
RETURNING id;`
var id int
expiresDays, err := strconv.ParseInt(expires, 10, 32)
if err != nil {
return 0, err
}
expiresInterval := pgtype.Interval{
Days: int32(expiresDays),
Status: pgtype.Present}
err = m.DB.QueryRow(context.Background(), stmt, title, content,
expiresInterval).Scan(&id)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return 0, models.ErrNoRecord
} else {
return 0, err
}
}
return 0, nil
}
- 2 回答
- 0 關注
- 217 瀏覽
添加回答
舉報