dppfxf909679
2017-04-13 08:38 阅读 26

向Postgres查询添加查询参数时出错

When I write the code:

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

Everything works fine. But I want it to not just get the page with id=1, but to be dynamic.

So I write:

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

But I get an error:

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

The full code:

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)
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dongyan1899 dongyan1899 2017-04-13 09:37

    psql driver uses $1, $2, etc for params:

    database.QueryRow("SELECT page_title,page_content,page_date FROM pages WHERE id = $1", pageID)
    
    点赞 评论 复制链接分享
  • duanqinqian5299 duanqinqian5299 2017-04-13 08:59

    QueryRow takes var args of type interface{}. It could be that pageID is being interpolated as a string (as returned by mux.Vars), resulting in a query that's incorrectly formatted as:

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

    Try converting pageID to int:

    id := vars["id"]
    pageID := strconv.Atoi(id)
    
    点赞 评论 复制链接分享

相关推荐