PDA

View Full Version : Escape string for insertion into Mysql db ??



BillGates
9th October 2010, 01:39
I know that q.bindValue(:placeholder, stringvar) will escape stringvar, but what I need is like escaped_str = mysql_real_escape_string(string) so that I can escape myself.


Any hints as to how to approach this problem ?

Lykurg
9th October 2010, 08:17
but what I need is like escaped_str = mysql_real_escape_string(string) so that I can escape myself.
Why? But if you really have to, use QSqlField for escaping.

BillGates
9th October 2010, 16:13
erm, thanks for replying, I was not aware of the existance of QSqlField, but i dont think it can help me.

i need something like :

qstring = "O'neill";
qstring = mysql_escape_string( qstring ); // qstring now O\'neill
...
query.exec("Insert Into table (col) Values ( qstring ) ");

Cheers!

Lykurg
9th October 2010, 16:36
erm, thanks for replying, I was not aware of the existance of QSqlField, but i dont think it can help me.Well, it could, but
i need something like :

qstring = "O'neill";
qstring = mysql_escape_string( qstring ); // qstring now O\'neill
...
query.exec("Insert Into table (col) Values ( qstring ) ");for that QSqlQuery::prepare and QSqlQuery::bindValue is exactly what you need.

Lykurg
9th October 2010, 16:48
Although we are not in the newbie section:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
db.open();

QString stringToEscape = "foo \" bar";
QSqlField f;
f.setType(QVariant::String);
f.setValue(stringToEscape);

qWarning() << stringToEscape;
qWarning() << db.driver()->formatValue(f);

"foo " bar"
"'foo " bar'"
But don't dare, don't even think of using that for your problem!

BillGates
17th October 2010, 00:48
ok, i tried your solution and appears to work, but why do you say it shouldnt be used ? what is problem ?

Lykurg
17th October 2010, 01:03
Because it is nonsense to do so if you have a prepare function. Even if I haven't checked, the prepare function is probably faster then doing the encoding yourself.

And I always would stick the the functions Qt provides you and I wouldn't do voodoo like going with QSqlField and QSqlDriver if there is no strong reason.

BillGates
17th October 2010, 12:11
OK, but what if what you want is just to write down (to a file) the query for later insertion ... you need to escape the string values.