14

I'm working with SQLite, doing insert into table. Folowwing

QSqlQuery testQuery(QString("INSERT INTO test(testcol) VALUES(?)"));
testQuery.bindValue(0, someQStringObg);
testQuery.exec();

works, but

QSqlQuery testQuery(QString("INSERT INTO test(testcol) VALUES(:val)"));
testQuery.bindValue(":val", someQStringObg);
testQuery.exec();

don't. testQuery.lastError().text() returns No query Unable to fetch row

Have no clue why things are that way, but really want to find out.

Toseef Khilji
  • 17,192
  • 12
  • 80
  • 121
user3136871
  • 245
  • 2
  • 3
  • 8
  • Which sql type and version are you using? Which Qt version? Which OS, which version? Have you tried explicit .prepate() call to see the return value? Also, it is strange that you mix the "?" and ":" approaches, though that should not matter. – László Papp Dec 26 '13 at 14:11
  • Try to print out the last query with this: `qDebug () << query->lastQuery()` just to make sure. What does that print out? Also, could you please check if the table exists properly before the insertion of the second case? You could use a command line client for double checking this. – László Papp Dec 26 '13 at 14:20
  • @LaszloPapp with prepare everything works! Thanks! – user3136871 Dec 26 '13 at 14:29
  • OK, great. Submitted an answer for better readability. – László Papp Dec 26 '13 at 14:30

1 Answers1

16

Please use prepare as the official example:

QSqlQuery testQuery;
testQuery.prepare("INSERT INTO test(testcol) VALUES(:val)");
testQuery.bindValue(":val", someQStringObj);
testQuery.exec();

The reason for the error is that the query was executed before binding to the corresponding placeholder. You can see the relevant part of the constructor documentation:

If query is not an empty string, it will be executed.

ABu
  • 10,423
  • 6
  • 52
  • 103
László Papp
  • 51,870
  • 39
  • 111
  • 135
  • Problem is that using constructor "If query is not an empty string, it will be executed." - So query was being executed before bind... – LS_ᴅᴇᴠ Dec 26 '13 at 14:32
  • "The reason for the error is that the query was executed before binding to the corresponding placeholder" – it doesn't look like the code that doesn't work executes the query before binding to the corresponding placeholder to me... Am I missing something? – HelloGoodbye Jan 17 '18 at 15:29