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

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

How to append URI as string in SQL query

问题

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

id是整数(int4)。

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

package main

import "fmt"
import "github.com/go-martini/martini"
import "net/http"
import "database/sql"
import _ "github.com/lib/pq"

func SetupDB() *sql.DB {
  db, err := sql.Open("postgres", "user=postgres password=apassword dbname=lesson4 sslmode=disable")
  PanicIf(err)
  return db
}

func PanicIf(err error) {
  if err != nil {
    panic(err)
  }
}

func main() {
  m := martini.Classic()
  m.Map(SetupDB())

  m.Get("/post/:idnumber", func(rw http.ResponseWriter, r *http.Request, db *sql.DB) {

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

    var title, author, description string
    for rows.Next() {
      err:= rows.Scan(&title, &author, &description)
      PanicIf(err)
      fmt.Fprintf(rw, "Title: %s\nAuthor: %s\nDescription: %s\n\n",
        title, author, description)
    }

  })

  m.Run()
}
英文:

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:

package main

import "fmt"
import "github.com/go-martini/martini"
import "net/http"
import "database/sql"
import _ "github.com/lib/pq"

func SetupDB() *sql.DB {
  db, err := sql.Open("postgres", "user=postgres password=apassword dbname=lesson4 sslmode=disable")
  PanicIf(err)
  return db
}

func PanicIf(err error) {
  if err != nil {
    panic(err)
  }
}

func main() {
  m := martini.Classic()
  m.Map(SetupDB())

  m.Get("/post/:idnumber", func(rw http.ResponseWriter, r *http.Request, db *sql.DB) {

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

    var title, author, description string
    for rows.Next() {
      err:= rows.Scan(&title, &author, &description)
      PanicIf(err)
      fmt.Fprintf(rw, "Title: %s\nAuthor: %s\nDescription: %s\n\n",
        title, author, description)
    }

  })

  m.Run()
}

答案1

得分: 1

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

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

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

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

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

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

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

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

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

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

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

改为:

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;

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

to;

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:

确定