看起來很簡單,但無法實現。 當瀏覽domain.com/post/1
時,它應顯示來自行id
的數據,其值爲1
。如何在SQL查詢中將URI附加爲字符串
行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()
}
當你說不工作你是什麼意思?它不是在sql中找到行嗎? –
我總是得不到它,並給出錯誤。嘗試過不同的方式。我只是不知道 – apasajja
我忘記了有關參數。 – apasajja