PDA

View Full Version : problem while executing SQL query



sosanjay
9th October 2009, 08:05
hello,

i'm able to connect with db[MySql].
i'm trying to Execute the Sql Query but i'm not getting wrong result.

I want to get the number of row in the current table.

My Query is :



QSqlQuery q1("SELECT COUNT(RecordId) FROM tbl;");
QSqlRecord rec1 = q1.record();
QString Str = q1.value(0).toString();
QMessageBox::information(this, tr("Count"),Str);


The result in message box is NULL.

if we run the sql query normally we get the result i.e 10;

What wrong in the query.

Lykurg
9th October 2009, 09:49
Try:
QSqlQuery q1("SELECT COUNT(RecordId) FROM tbl;");
if(q1.next())
qWarning() << "sql-return:" << q1.value(0).toInt();

EDIT: and use the second parameter for the query constructor to set the database connection, to make sure you querying the right database.

vcp
9th October 2009, 12:09
Hi

Try this:

Note the: exec()



QSqlQuery q1("SELECT COUNT(RecordId) FROM tbl;");
q1.exec();
if(q1.next())
qWarning() << "sql-return:" << q1.value(0).toInt();

Lykurg
9th October 2009, 12:52
Note the: exec()
You don't need that. The doc says:
QSqlQuery::QSqlQuery ( const QString & query = QString(), QSqlDatabase db = QSqlDatabase() )
Constructs a QSqlQuery object using the SQL query and the database db. If db is not specified, the application's default database is used. If query is not an empty string, it will be executed.