将变量传递给GoLang查询 [英] Passing Variable to GoLang Query

查看:46
本文介绍了将变量传递给GoLang查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我要说我是golang的初学者(从几天前开始),目前正在学习如何实际应用该语言.我的目标是建立一个Web Rest API,该API可以查询数据库并将数据提供给用户.

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.

我已经能够使用martini成功创建一个简单的API( https://github.com/go-martini/martini ),然后使用 https://github连接到MySQL数据库.com/go-sql-driver/mysql .目前,我的问题是如何将API请求中的变量参数传递到我的查询中.这是我当前的代码:

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()  

}

如您所见,我的目标是获取输入变量(用户)并将其插入到名为userId的变量中.然后,我想针对该变量查询数据库以获取名称.一旦一切正常,我想用用户名回复.

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.

任何人都可以帮忙吗?当我继续学习Go的过程时,将不胜感激!

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

推荐答案

我没有用过,但是看一下文档,这是您要的吗?

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)

我认为它应该以sql安全的方式将?替换为 userId .

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

http://golang.org/pkg/database/sql/#DB.查询

这篇关于将变量传递给GoLang查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆