doucan8521 2015-03-17 03:14
浏览 96
已采纳

将变量传递给GoLang查询

first off let me say I'm a beginner (started a few days ago) with golang and am in the process of learning how to practically apply the language. My goal is to build a web Rest API that queries a database and provides data back to the user.

I've been able to successfully create a simple API using martini (https://github.com/go-martini/martini) and connect to a MySQL database using https://github.com/go-sql-driver/mysql. My problem at the current moment is how to pass a variable param from the API request into my query. Here is my current code:

package main

import (
    "github.com/go-martini/martini"
    _ "github.com/go-sql-driver/mysql"
    "database/sql"
    "fmt"
)

func main() {

  db, err := sql.Open("mysql",
    "root:root@tcp(localhost:8889)/test")

  m := martini.Classic()

  var str string

  m.Get("/hello/:user", func(params martini.Params) string {

  var userId = params["user"] 

  err = db.QueryRow(
      "select name from users where id = userId").Scan(&str)

  if err != nil && err != sql.ErrNoRows {
    fmt.Println(err)
  }

  return "Hello " + str

  })

  m.Run()


  defer db.Close()  

}

As you can see my goal is to take the input variable (user) and insert that into a variable called userId. Then I'd like to query the database against that variable to fetch the name. Once that all works I'd like to respond back with the name of the user.

Can anyone help? It would be much appreciated as I continue my journey to learn Go!

  • 写回答

1条回答 默认 最新

  • dsfsda121545 2015-03-17 03:51
    关注

    I haven't used it, but looking at the docs, is this what you are after?

    db.QueryRow("SELECT name FROM users WHERE id=?", userId)
    

    I assume it should replace the ? with userId in a sql safe way.

    http://golang.org/pkg/database/sql/#DB.Query

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?