Passing Variable to GoLang Query

本小妞迷上赌 提交于 2021-02-07 12:49:17

问题


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:


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



来源:https://stackoverflow.com/questions/29090705/passing-variable-to-golang-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!