samwell
samwell

Reputation: 2797

Sanitizing input with C++

I'm trying to sanitize my input for a SQLite database and I'm using sqlite3_mprintf to do it, but I'm getting some weird results. I tried different variations, am I doing something wrong?

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)

Upvotes: 0

Views: 2060

Answers (2)

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

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

These are both correct. '' is an escaped quote. The %Q option just adds the surrounding quotes itself.

Upvotes: 4

Mohammed Hossain
Mohammed Hossain

Reputation: 1319

According to the documentation, that is expected behavior. The documentation also states that:

As a general rule you should always use %q instead of %s when inserting text into a string literal.

Upvotes: 1

Related Questions