Golang查询字符串作为查询的一部分

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".

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.

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.