PDA

View Full Version : How to insert mixed (double/single) quotes into sqlite database?



binary001
23rd April 2016, 16:36
Hi,

I want to save some sentences into sqlite database. These sentences contains mixed single quotes and qouble quotes.

sample sentence is:
Homer Simpson said: "Maybe, just once, someone will call me 'Sir' without adding 'you're making a scene'."

I want to assign these words to string and then insert into database.

QString str1 ="Homer Simpson said: "Maybe, just once, someone will call me 'Sir' without adding 'you're making a scene'."";

str1.replace(QString("'"),QString("\'"));
str1.replace(0x22,QString("\""));

query->exec("insert into greatquote values(" + QString::number(intNo) + ", '" + str1 + "')";

Sample sentence can't assign to str1. How can I change these words with escape special characters? Which functions I use?
Finally how to insert these into sqlite database?

Thanks

anda_skoa
23rd April 2016, 16:59
You are trying to manually include the parameters in the query by concatenating strings, while you should be allowing the SQL engine to do it.
See QSqlQuery::prepare().

Cheers,
_

ChrisW67
23rd April 2016, 22:25
If this sentence:

Homer Simpson said, "Maybe, just once, someone will call me 'Sir' without adding 'you're making a scene'."
Is to appear as a literal string in your C++ code (as in your example) then you must escape the embedded double quotes:


QString str1 ="Homer Simpson said, \"Maybe, just once, someone will call me 'Sir' without adding 'you're making a scene'.\"";

This is before you do what anda_skoa suggests and use parameter binding to do the SQL insert safely.

binary001
24th April 2016, 06:27
Thanks you for your suggestions.

It's working with QSqlQuery::prepare() and addBindValue.