1

I would like to use string as part of query.

func GetAll(id int) {
  var queryPart string
  if id != 0 {
    queryPart = fmt.Sprintf("WHERE id = %d", id)
  } else {
    queryPart = ""
  }


  database.DB.Query("SELECT name FROM table ?, queryPart)
}

In database.DB I've got *db.Sql instance.

How to get it work? With that code I still get "You have an error in your SQL syntax".

2 Answers 2

5

You can build your query gradually, only adding the arguments if required.

// Build a query (columns and table being strings)
q := fmt.Sprintf("SELECT %s FROM %s", columns, table)
args := []interface{}{}

// Add conditional query/args
if id != 0 {
 q = fmt.Sprintf("%s WHERE id=?",q)
 args = append(args,id)    
}

// Perform the query
database.DB.Query(q,args...)

If you find yourself doing a lot of this, consider writing a small query builder which will let you easily build sql queries without so much fuss. It can be relatively simple, with slots for select, joins etc and an array for args.

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

4 Comments

@mkopriva thanks for the edit, I was editing at the same time and it clashed I think.
I saw that, no worries ;)
Perfect, if you got some example of your simple query builder, I would really like to see it :)
The one I wrote/use is here, it may or may not suit you or provide a useful ref github.com/fragmenta/query
1

Placeholders (?) are for variables only, not statements.

You should instead have two separate queries:

  if id != 0 {
    database.DB.Query("SELECT name FROM table WHERE id = ?", id)
  } else {
    database.DB.Query("SELECT name FROM table")
  }

Additionally: using Sprintf("WHERE id = %d", id) defeats the purpose of placeholders.

2 Comments

Is it the only way? I've got mega complicated query and I don't want to duplicate code.
@nexequ you can concatenate your query string with + and collect arguments into a slice with append, and then, at the end, execute the query like so: Query(queryString, args...).

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.