0

当我写代码时:

err := database.QueryRow("SELECT page_title,page_content,page_date FROM pages WHERE id=1").
    Scan(&thisPage.Title, &thisPage.Content, &thisPage.Date)

一切正常。但我希望它不仅可以获取带有 的页面id=1,而且还可以是动态的。

所以我写:

err := database.QueryRow("SELECT page_title,page_content,page_date FROM pages WHERE id=?", pageID).
    Scan(&thisPage.Title, &thisPage.Content, &thisPage.Date)

但我收到一个错误:

GolangdProjects go run test.go  
1  
2017/04/13 11:29:57 Couldn't get page: 1  
exit status 1

完整代码:

package main

import (
  "database/sql"
  "fmt"
  _ "github.com/lib/pq"
  "github.com/gorilla/mux"
  "log"
  "net/http"
)

const (
  DBHost = "localhost"
  DBPort = ":5432"
  DBUser = "nirgalon"
  DBPass = ""
  DBDbase = "cms"
  PORT = ":8080"
)

var database *sql.DB

type Page struct {
  Title string
  Content string
  Date string
}

func ServePage(w http.ResponseWriter, r *http.Request) {
  vars := mux.Vars(r)
  pageID := vars["id"]
  thisPage := Page{}
  fmt.Println(pageID)
  err := database.QueryRow("SELECT page_title,page_content,page_date FROM pages WHERE id=1").Scan(&thisPage.Title, &thisPage.Content, &thisPage.Date)
  if err != nil {
    log.Fatal("Couldn't get page: " + pageID)
    log.Fatal(err.Error)
  }
  html := `<html><head><title>` + thisPage.Title + `</title></head><body><h1>` + thisPage.Title + `</h1><div>` + thisPage.Content + `</div></body></html>`
  fmt.Fprintln(w, html)
}

func main() {
  db, err := sql.Open("postgres", "user=nirgalon dbname=cms sslmode=disable")
  if err != nil {
    log.Println("Couldn't connnect to db")
    log.Fatal(err)
  }
  database = db

  routes := mux.NewRouter()
  routes.HandleFunc("/page/{id:[0-9]+}", ServePage)
  http.Handle("/", routes)
  http.ListenAndServe(PORT, nil)
}
4

2 回答 2

1

psql 驱动程序使用$1,$2等作为参数:

database.QueryRow("SELECT page_title,page_content,page_date FROM pages WHERE id = $1", pageID)
于 2017-04-13T09:37:02.857 回答
0

QueryRow采用 var args 类型interface{}。可能pageID是被插入为字符串(由 返回mux.Vars),导致查询的格式不正确:

"SELECT page_title,page_content,page_date FROM pages WHERE id='1'"

尝试转换pageID为int:

id := vars["id"]
pageID := strconv.Atoi(id)
于 2017-04-13T08:59:24.293 回答