sqlite3_mprintf – 我应该总是使用%Q作为格式说明符而不是%s吗?

前端之家收集整理的这篇文章主要介绍了sqlite3_mprintf – 我应该总是使用%Q作为格式说明符而不是%s吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
摘自sqlite对sqlite3_mprintf()API的引用

http://www.sqlite.org/c3ref/mprintf.html

“%Q选项的作用类似于%q,除了它还在整个字符串的外部添加单引号.此外,如果参数列表中的参数是NULL指针,%Q将替换文本”NULL“(不带单引号) “.

使用%q时,我们必须小心使用它周围的单引号,例如

char *zText = "It's a happy day!";
char *zsql = sqlite3_mprintf("INSERT INTO table VALUES('%q')",zText);

总是使用%Q而不是%q似乎更方便,如下所示:

char *zsql = sqlite3_mprintf("INSERT INTO table VALUES(%Q)",zText);

我的问题 – 是否有一个有效的用例,其中’%q’更合适或更有效?或者我可以安全地使用%Q作为所有语句中%s的替代?

解决方法

一切都将以安全的方式创建sql语句,以最大限度地减少sql注入的可能性.

您应该始终优先选择%q而不是%s.

The %q option works like %s in that it substitutes a nul-terminated string from the argument list. But %q also doubles every '\'' character. %q is designed for use inside a string literal. By doubling each '\'' character it escapes that character and allows it to be inserted into the string.

%Q比%q具有更多优势.

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

这意味着它将添加单引号,并将nul指针呈现为字符串内的字符串文字“NULL”.

正如您所看到的,这取决于您想要做什么.如果你可以添加单引号和“NULL”生成行为,你可以简单地使用%Q(我认为它对sql语句中的参数值非常有意义).也许有时你不想要这种行为然后你可以回到%q.

猜你在找的Sqlite相关文章