10

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
  • You might find the following resource to be useful in your SQL + go adventures: go-database-sql.org Commented Mar 18, 2015 at 19:52

2 Answers 2

20

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

Sign up to request clarification or add additional context in comments.

3 Comments

Correct. ? is the parameter format used by mySQL, and $1, $2, etc. is the PostgreSQL format. The OP should NEVER (ever!) use anything but parameterisation else they be subject to SQL injection attacks.
Thanks that helped a lot. @elithrar am I doing the correct parameterization in my above example? Ex. var userId = params["user"]
The parameterisation I'm talking about is in your SQL query - not your Go code. You should read blog.codinghorror.com/… to get a better understanding of what I mean and why you want to do it.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.