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

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

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据