dongyi0210 2015-04-22 16:48
浏览 40
已采纳

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

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
Author: %s
Description: %s

",
        title, author, description)
    }

  })

  m.Run()
}
  • 写回答

2条回答 默认 最新

  • dousi1097 2015-04-22 16:53
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵