gpt4 book ai didi

sqlite3_mprintf - 我是否应该始终使用 %Q 作为格式说明符而不是 %s?

转载 作者:行者123 更新时间:2023-12-03 16:22:04 25 4
gpt4 key购买 nike

摘自 sqlite3_mprintf() API 上的 SQLite 引用资料

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 注入(inject)的可能性。

你应该更喜欢 %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 .

关于sqlite3_mprintf - 我是否应该始终使用 %Q 作为格式说明符而不是 %s?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10522126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com