-1

I have a sql select statement like this example:

queryValues = make([]interface{}, 0, 5)

queryValues = append(Name, obj.Name)
queryValues = append(Age, obj.Age)
whereClause := "where name = $1 and age = $2"    

query := fmt.Sprintf("Select * from Table1  %s;", whereClause)

rows, err := dbConnection.Query(query, queryValues...)

I have several questions here. What is the ... after queryValues? How come when I look at the query being passed up to the db none of the $1 are actually being converted into there real values?

What print function can I run to mimic dbConnection.Query(query, queryValues...) so that I can see it before it is passed up?

Thanks in advance.

Josh

Josh
  • 569
  • 1
  • 11
  • 35
  • `...` is passing a slice as varargs. You should always append to your `queryValues` slice, not to `Name` and `Age`. I guess your code doesn't even compile. Even if it does, `queryValue` will not be what you think it is. – icza Jun 08 '15 at 16:51
  • @icza I had to use Pseudo code because my actual code is company propriety. So What print method can I used to have it append those values in the slice to there corresponding $ number in the original string? – Josh Jun 08 '15 at 16:53

1 Answers1

0

The answer to your first question is that Query is what's referred to as a variadic function https://golang.org/ref/spec#Function_types. It takes any number of parameters of the last type, and is handed to the function as a slice.

queryValues... is the reverse of that. It is taking your slice and passing them as individual arguments to query. It's doing the same thing as if you had done:

dbConnection.Query(query, queryValues[0], queryValues[1])

https://golang.org/ref/spec#Passing_arguments_to_..._parameters

In this particular case you don't need the []interface{}

dbConnection(query, obj.Name, obj.Age)

The reason your $1, $2 placeholders are not being converted is likely because you're using the wrong placeholders for the particular driver you're using. It's dependent on the driver itself. For instance the MySQL driver uses '?' as it's placeholder.

Erik St. Martin
  • 584
  • 3
  • 4