Cant seem to escape a query i am sending to my sqlite3 db, not sure why

c++, prepared-statement, sql, sqlite

Solution

In SQL, strings use single quotes, and are escaped by using two single quotes. (Double quotes are accepted for compatibility with MySQL, but should not be used.)

Your query should look like this:

INSERT OR REPLACE INTO TableA(a, b, c)
VALUES (1, 'I have a 3" gauge', 'I am looking for 3/8" thickness')

or like this:

INSERT OR REPLACE INTO TableA(a, b, c)
VALUES (1, "I have a 3"" gauge", "I am looking for 3/8"" thickness")

However, to avoid string formatting problems, it is recommended to use parameters. This is how it works with direct SQLite function calls (wrappers might work differently):

const char *sql = "INSERT OR REPLACE INTO TableA(a, b, c) VALUES (1, ?, ?)";
sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
sqlite3_bind_text(stmt, 1, "I have a 3\" gauge", -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 2, "I am looking for 3/8\" thickness", -1, SQLITE_TRANSIENT);

Problem

I have a string as such: ``` string query; query = "insert or replace into TABLEA (a,b,c) values (@a,\"@b\",\"@c\");"; ``` that way i can insert strings into B and C with just a simple replace: ``` string instring("I have a 3\" gauge"); string instring2("I am looking for 1/8\" thickness"); Replace(&query, "@a", to_string(1)); Replace(&query, "@b", instring); Replace(&query, "@c", instring2); ``` So now my query string is: ``` "insert or replace into TABLEA (a,b,c) values (1,\"I have a 3\" gauge\",\"I am looking for 1/8\" thickness\");"; ``` SQLITE3 gets it and it looks like: ``` insert or replace into TABLEA (a,b,c) values (1,"I have a 3" gauge","I am looking for 1/8" thickness"); ``` The issue is that the strings end prematurely. I tried to add additional escape characters but that wasnt seeming to work either. Right now i am using sqlite3_exec() to carry out everything. Is there something else i should do? Does a prepared statement handle what i am trying to do? Should i just try it with prepared_v2 and that might resolve issues? How should i be approaching this?

Original source

Related problems