Wojciech Sobczyk
Wojciech Sobczyk

Reputation: 343

QSqlQuery constructor strange behavior

QMake version 3.0

Qt version 5.0.2

When using

QSqlQuery query(QString("SELECT device_text_id FROM device"));
qDebug() << query.exec();

i get false in query.exec() and no results returned in query object but when I use

QSqlQuery query;
query.prepare("SELECT device_text_id FROM device");
qDebug() << query.exec();

i get true and correct data returned.

In documentation of QSqlQuery is a constructor beeing used in both of cases above:

QSqlQuery(const QString & query = QString(), QSqlDatabase db = QSqlDatabase())

For more info I checked my postgres (v9.1) logs. I hit this error every time the query is executed in the first way presented.

CET ERROR:  syntax error at end of input at character 9
CET STATEMENT:  EXECUTE 

Am I missing something? Why the first approach is not working?

Upvotes: 1

Views: 225

Answers (1)

sth
sth

Reputation: 229784

Calling the constructor with a string directly executes that query. The query already got executed once the object is constructed.

When you then call .exec(), it tries to execute a query that got prepared with prepare(). But there was no prepare(), so that attempt fails. This failure causes the return value false that you see in the program.

Upvotes: 2

Related Questions