我正在尝试运行这个简单的查询来返回 id,根据作者的说法,我们使用 QueryRow 函数,好的,但是这个查询结果返回了一个期望 2 个 args 但在这里某处收到 3 个错误。
查询模型.go
type WidgetetModel struct {
DB *pgxpool.Pool
}
func (m *WidgetModel) Insert(title, content, expires string) (int, error) {
stmt := `INSERT INTO widgets (title, content, created, expires) VALUES($1, $2, NOW(), NOW() + INTERVAL '$3 day') RETURNING id;`
var id int
err := m.DB.QueryRow(context.Background(), stmt, title, content, expires).Scan(&id)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return 0, models.ErrNoRecord
} else {
return 0, err
}
}
return 0, nil
}
处理程序.go
func (app *application) createWidget(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
app.clientError(w, http.StatusMethodNotAllowed) // Use the clientError() helper.
return
}
title := "Widget 1"
content := "Some content here..."
expires := "7"
id, err := app.widgets.Insert(title, content, expires)
if err != nil {
app.serverError(w, err) <-- line 57
return
}
http.Redirect(w, r, fmt.Sprintf("/widget?id=%v", id), http.StatusSeeOther)
}
main.go
我只是在这里使用一个结构来为我的处理程序注入依赖项。
dbPool, err := openDB(*dsn)
if err != nil {
errorLog.Fatal(err)
}
defer dbPool.Close()
app := &application{
errorLog: errorLog,
infoLog: infoLog,
snippets: &postgresql.WidgetModel{DB: dbPool},
}
///
func openDB(dsn string) (*pgxpool.Pool, error) {
pool, err := pgxpool.Connect(context.Background(), dsn)
if err != nil {
return nil, err
}
if err = pool.Ping(context.Background()); err != nil {
return nil, err
}
return pool, nil
}
哈士奇WWW
哆啦的时光机
当年话下
随时随地看视频慕课网APP
相关分类