Excerpt from SQLite reference on sqlite3_mprintf() API
http://www.sqlite.org/c3ref/mprintf.html
“The %Q option works like %q except it also adds single quotes around the outside of the total string. Additionally, if the parameter in the argument list is a NULL pointer, %Q substitutes the text “NULL” (without single quotes).”
When using %q, we have to be careful to always use single quotes around it e.g.
char *zText = "It's a happy day!";
char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
It seems more convenient to always use %Q instead of %q as follows:
char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
My question – is there a valid use case where ‘%q’ is more suitable or more efficient? Or can I safely use %Q as a replacement for %s in all statements?
Everything is about to create SQL-statements in a secure way to minimize the possibility of SQL-injections.
You should prefer
%qover%sall the time.The
%Qhas some futher advantages over%q.This means it will add single quotes and it will render nul pointers as the string literal
"NULL"inside the string.As you can see it depends on what you want to do. If you are ok with adding single quotes and that
"NULL"generating behavior you can simply use%Q(I think it makes highly sense for paramter values in SQL-statements). Maybe sometimes you dont want this behavior then you can fall back to%q.