I am using go-mysql-driver to make queries to my database. I have a function In which I am passing id
and warehouseId
.
Now I am modifying my mysql query based on if warehouseId value is 0 or not.
The problem is the parameters that I pass in db.Query()
. Following is my mysql query
where I am appending additional query if warehouseId
is not 0
.
query := "select id,description from offers inner join offer_entities on offers.id = offer_entities.offer_id where offer_entities.entity_id = ?"
if warehouseId != 0 {
query += `and offer_entities.warehouse_id = ? `
}
query += `group by offer_id`
I parse it like this:
if warehouseId != 0 {
rows, err := db.Query(query, variantId, warehouseId)
} else {
rows, err := db.Query(query, variantId)
}
However, the problem is when I run it, I get an error undefined: rows
. I know that it is because rows
should be defined outside the if-else
conditions. But I don't understand how to define rows outside if-else or If there is any other way I could achieve my requirements.
How should I tackle this problem.
Thanks in advance.
the problem is because of variables are defined in the scope in which they are declared.
The difference between = and := is that = is just assignment and := is used for assignment and declaration
for example
rows := 1
//it basically means
var rows int
rows = 1
what you want is to declare rows outside the if-else and then use them, will solve the problem.
Each block has itself visibility scope. A general rule is visible from inner, invisible from outer. It means you can see variables from superior scope in subject scope but not vise versa.
I believe you use rows
declared in if
statement out of the block, so it doesn't exist there.
var err error
var rows string
if warehouseId != 0 {
rows, err := db.Query(query, variantId, warehouseId)
} else {
rows, err := db.Query(query, variantId)
}
fmt.Println(rows) // It is now possible to use `rows` outside of the block
var name <type>
is a common declaration way. The variable with typed nil
value will be declared.
name := <value of type>
is a short declaration form. It will declare a variable of a type and assign a value to it at the same time. Allowed only in functions.