postgresql - How to append URI as string in SQL query -
looks simple unable make happen. when browsing domain.com/post/1
, should show data row id
value 1
.
row id
integer (int4
).
below the codes, 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 books id = params["idnumber"]`) panicif(err) defer rows.close() var title, author, description string 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() }
part of issue you're using string params["idnumber"]
part of sql query
db.query(`select title, author, description books id = params["idnumber"]`)
that book id equals params["idnumber"]
string.
what need use placeholders , arguments according http://golang.org/pkg/database/sql/#db.query
in case query should
db.query("select title, author, description books id=$1", params["idnumber"])
that should solve issue think you're having. however, until update question actual issue you're having won't know.
update
the error you're getting undefined: params
because don't have params object in scope.
i'd suggest reading how martini works in regards of getting arguments out of route. https://github.com/go-martini/martini#routing
Comments
Post a Comment