Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Variable to GoLang Query

Tags:

mysql

go

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!

like image 643
viablepath Avatar asked Mar 17 '15 03:03

viablepath


2 Answers

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

like image 169
Drew LeSueur Avatar answered Sep 30 '22 19:09

Drew LeSueur


You can try it this way.

var y string // Variable to store result from query.
err := db.QueryRow("SELECT name from user WHERE id = $1", jobID).Scan(&y)
if err != nil && err != sql.ErrNoRows {
    fmt.Println(err)
}   

Documentation reference: https://pkg.go.dev/database/sql#pkg-variables

like image 28
Yash Chauhan Avatar answered Sep 30 '22 18:09

Yash Chauhan