使用C ++清理输入

时间:2013-03-21 19:02:03

标签: c++ sqlite

我正在尝试清理我对SQLite数据库的输入,并且我正在使用sqlite3_mprintf来完成它,但我得到了一些奇怪的结果。我尝试了不同的变化,我做错了吗?

const char * zChar = "It's a nice day";
cout << sqlite3_mprintf("INSERT INTO table(col1) VALUES('%Q')", zChar) << endl;
//INSERT INTO table(col1) VALUES(''It''s a nice day'')

cout << sqlite3_mprintf("INSERT INTO table(col1) VALUES(%Q)", zChar) << endl;
//INSERT INTO table(col1) VALUES('It''s a nice day')

cout << sqlite3_mprintf("INSERT INTO table(col1) VALUES('%q')", zChar) << endl;
//INSERT INTO table(col1) VALUES('It''s a nice day')

cout << sqlite3_mprintf("INSERT INTO table(col1) VALUES(%q)", zChar) << endl;
//INSERT INTO table(col1) VALUES(It''s a nice day)

2 个答案:

答案 0 :(得分:3)

sqlite3_mprintf("INSERT INTO table(col1) VALUES(%Q)", zChar)
//INSERT INTO table(col1) VALUES('It''s a nice day')

sqlite3_mprintf("INSERT INTO table(col1) VALUES('%q')", zChar)
//INSERT INTO table(col1) VALUES('It''s a nice day')

这些都是正确的。 ''是一个转义报价。 %Q选项只会添加周围的引号本身。

答案 1 :(得分:1)

根据the documentation,这是预期的行为。该文件还指出:

  

作为一般规则,您应该始终使用%q而不是%s   将文本插入字符串文字。

相关问题