将查询参数添加到PostgreSQL查询时出现错误。

huangapple go评论90阅读模式
英文:

Error when add a query parameter to postgres query

问题

当我写下这段代码时:

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)
}
英文:

When I write the code:

err := database.QueryRow(&quot;SELECT page_title,page_content,page_date FROM pages WHERE id=1&quot;).
Scan(&amp;thisPage.Title, &amp;thisPage.Content, &amp;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(&quot;SELECT page_title,page_content,page_date FROM pages WHERE id=?&quot;, pageID).
Scan(&amp;thisPage.Title, &amp;thisPage.Content, &amp;thisPage.Date)

But I get an error:

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

The full code:

package main
import (
&quot;database/sql&quot;
&quot;fmt&quot;
_ &quot;github.com/lib/pq&quot;
&quot;github.com/gorilla/mux&quot;
&quot;log&quot;
&quot;net/http&quot;
)
const (
DBHost = &quot;localhost&quot;
DBPort = &quot;:5432&quot;
DBUser = &quot;nirgalon&quot;
DBPass = &quot;&quot;
DBDbase = &quot;cms&quot;
PORT = &quot;:8080&quot;
)
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[&quot;id&quot;]
thisPage := Page{}
fmt.Println(pageID)
err := database.QueryRow(&quot;SELECT page_title,page_content,page_date FROM pages WHERE id=1&quot;).Scan(&amp;thisPage.Title, &amp;thisPage.Content, &amp;thisPage.Date)
if err != nil {
log.Fatal(&quot;Couldn&#39;t get page: &quot; + pageID)
log.Fatal(err.Error)
}
html := `&lt;html&gt;&lt;head&gt;&lt;title&gt;` + thisPage.Title + `&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;` + thisPage.Title + `&lt;/h1&gt;&lt;div&gt;` + thisPage.Content + `&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;`
fmt.Fprintln(w, html)
}
func main() {
db, err := sql.Open(&quot;postgres&quot;, &quot;user=nirgalon dbname=cms sslmode=disable&quot;)
if err != nil {
log.Println(&quot;Couldn&#39;t connnect to db&quot;)
log.Fatal(err)
}
database = db
routes := mux.NewRouter()
routes.HandleFunc(&quot;/page/{id:[0-9]+}&quot;, ServePage)
http.Handle(&quot;/&quot;, routes)
http.ListenAndServe(PORT, nil)
}

答案1

得分: 1

psql驱动程序在参数中使用$1$2等:

database.QueryRow("SELECT page_title,page_content,page_date FROM pages WHERE id = $1", pageID)
英文:

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

database.QueryRow(&quot;SELECT page_title,page_content,page_date FROM pages WHERE id = $1&quot;, pageID)

答案2

得分: 0

QueryRow接受类型为interface{}的可变参数。可能是pageID被插入为字符串(由mux.Vars返回),导致查询格式不正确,如下所示:

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

尝试将pageID转换为整数:

id := vars["id"]
pageID := strconv.Atoi(id)
英文:

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:

&quot;SELECT page_title,page_content,page_date FROM pages WHERE id=&#39;1&#39;&quot;

Try converting pageID to int:

id := vars[&quot;id&quot;]
pageID := strconv.Atoi(id)

huangapple
  • 本文由 发表于 2017年4月13日 16:38:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/43387383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定