如何在 SQL 查询中将 URI 作为字符串附加?

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

How to append URI as string in SQL query

问题

看起来很简单,但我无法实现它。
当浏览domain.com/post/1时,应该显示id值为1的行的数据。

id是整数(int4)。

以下是代码,但它不起作用:

  1. package main
  2. import "fmt"
  3. import "github.com/go-martini/martini"
  4. import "net/http"
  5. import "database/sql"
  6. import _ "github.com/lib/pq"
  7. func SetupDB() *sql.DB {
  8. db, err := sql.Open("postgres", "user=postgres password=apassword dbname=lesson4 sslmode=disable")
  9. PanicIf(err)
  10. return db
  11. }
  12. func PanicIf(err error) {
  13. if err != nil {
  14. panic(err)
  15. }
  16. }
  17. func main() {
  18. m := martini.Classic()
  19. m.Map(SetupDB())
  20. m.Get("/post/:idnumber", func(rw http.ResponseWriter, r *http.Request, db *sql.DB) {
  21. rows, err := db.Query(`SELECT title, author, description FROM books WHERE id = params["idnumber"]`)
  22. PanicIf(err)
  23. defer rows.Close()
  24. var title, author, description string
  25. for rows.Next() {
  26. err:= rows.Scan(&title, &author, &description)
  27. PanicIf(err)
  28. fmt.Fprintf(rw, "Title: %s\nAuthor: %s\nDescription: %s\n\n",
  29. title, author, description)
  30. }
  31. })
  32. m.Run()
  33. }
英文:

Looks simple but I unable to make it happen.
When browsing domain.com/post/1, it should show data from row id which value 1.

Row id is integer (int4).

Below the the codes, which is not working:

  1. package main
  2. import "fmt"
  3. import "github.com/go-martini/martini"
  4. import "net/http"
  5. import "database/sql"
  6. import _ "github.com/lib/pq"
  7. func SetupDB() *sql.DB {
  8. db, err := sql.Open("postgres", "user=postgres password=apassword dbname=lesson4 sslmode=disable")
  9. PanicIf(err)
  10. return db
  11. }
  12. func PanicIf(err error) {
  13. if err != nil {
  14. panic(err)
  15. }
  16. }
  17. func main() {
  18. m := martini.Classic()
  19. m.Map(SetupDB())
  20. m.Get("/post/:idnumber", func(rw http.ResponseWriter, r *http.Request, db *sql.DB) {
  21. rows, err := db.Query(`SELECT title, author, description FROM books WHERE id = params["idnumber"]`)
  22. PanicIf(err)
  23. defer rows.Close()
  24. var title, author, description string
  25. for rows.Next() {
  26. err:= rows.Scan(&title, &author, &description)
  27. PanicIf(err)
  28. fmt.Fprintf(rw, "Title: %s\nAuthor: %s\nDescription: %s\n\n",
  29. title, author, description)
  30. }
  31. })
  32. m.Run()
  33. }

答案1

得分: 1

你的问题的一部分是你在 SQL 查询中使用了字符串 params["idnumber"]

  1. db.Query(`SELECT title, author, description FROM books WHERE id = params["idnumber"]`)

这将查找一个 id 等于 params["idnumber"] 字符串的书籍。

你需要使用占位符和参数,参考 http://golang.org/pkg/database/sql/#DB.Query

在这种情况下,你的查询应该是:

  1. db.Query("SELECT title, author, description FROM books WHERE id=$1", params["idnumber"])

这应该解决你遇到的问题。然而,在你实际更新你的问题并提供实际问题之前,我无法确定。

更新

你得到的错误 undefined: params 是因为你的作用域中没有 params 对象。

我建议你阅读一下 martini 如何在路由中获取参数的工作原理。https://github.com/go-martini/martini#routing

英文:

Part of your issue is that you're using the string params["idnumber"] as part of the SQL query

  1. db.Query(`SELECT title, author, description FROM books WHERE id = params["idnumber"]`)

That will look for a book where the id equals params["idnumber"] string.

What you need to do is use placeholders and the arguments according to http://golang.org/pkg/database/sql/#DB.Query

In this case your query should be

  1. db.Query("SELECT title, author, description FROM books WHERE id=$1", params["idnumber"])

That should solve the issue I think you're having. However, until you actually update your question with the actual issue you're having I won't know.

Update

The error you're getting with undefined: params is because you don't have a params object in scope.

I'd suggest reading how martini works in regards of getting the arguments out of the route. https://github.com/go-martini/martini#routing

答案2

得分: 1

我认为问题在于你在字符串文字查询中使用了变量名,而你想要的是它的值。

尝试将这段代码进行更改:

  1. rows, err := db.Query(`SELECT title, author, description FROM books WHERE id = params["idnumber"]`)

改为:

  1. rows, err := db.Query("SELECT title, author, description FROM books WHERE id =$1", params["idnumber"])

除此之外,你可能还有其他问题,但是考虑到你没有正确构建查询,我不会期望你能得到你想要的结果。

英文:

I think the problem is that you're using the variable name in your string literal query, you want it's value there instead.

Try changing this;

  1. rows, err := db.Query(`SELECT title, author, description FROM books WHERE id = params["idnumber"]`)

to;

  1. rows, err := db.Query("SELECT title, author, description FROM books WHERE id =$1", params["idnumber"])

You could have other issues beyond that but given you're not forming the query correctly I wouldn't expect you to get back the results you want.

huangapple
  • 本文由 发表于 2015年4月23日 00:48:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/29804035.html
匿名

发表评论

匿名网友

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

确定