PDA

View Full Version : SQL command and QString?



SunnySan
11th September 2008, 15:42
I would like to get the last ID of the table (plandfile)
I got the SQL code for it which gives me a nice single string under:


SELECT id FROM plandfile WHERE id=(SELECT MAX(id) FROM plandfile)

what would be the best way to transform this to a QString??
Is there a method of QSqlquery which return a String??
Please help
Thanks

wysota
11th September 2008, 16:43
See QSqlQuery::value() and QVariant::toString().

SunnySan
11th September 2008, 17:06
I have tried to test it


QVariant variant;
QSqlQuery query;
query.exec("SELECT id FROM plandfile WHERE id=(SELECT MAX(id) FROM plandfile)");
variant= query.value(0);// also try with 1
QString plandfileID;

plandfileID=variant.toString();
QMessageBox::about(this, tr("Value of ID"),plandfileID);

but I receive nothing in the QString.
I tested the SQL alone, works fine.
No Error but I m not sure why it's not working???

wysota
11th September 2008, 17:14
You have to call QSqlQuery::next() before you start reading values.

sadjoker
11th September 2008, 18:13
Something like this:



QSqlQuery query;
QString plandfileID;

query.exec("SELECT id FROM plandfile WHERE id=(SELECT MAX(id) FROM plandfile)");

while (query.next()) {
plandfileID = query.value(0).toString();
}

QMessageBox::about(this, tr("Value of ID"),plandfileID);

fnmblot
11th September 2008, 18:31
This is how I get the last entry.


QSqlQuery query("SELECT uid from main");
query.last();
Then I set that to be the max of my uidSpinbox

fvui.uidSpinBox->setMaximum(query.value(0).toInt());

jacek
11th September 2008, 19:23
This is how I get the last entry.


QSqlQuery query("SELECT uid from main");
query.last();
Then I set that to be the max of my uidSpinbox
You select the whole table to get one specific record? What a waste of resources. Also the database returns records in a random order.

To get the maximum uid use: SELECT MAX(uid) from main

jacek
11th September 2008, 19:25
I got the SQL code for it which gives me a nice single string under:


SELECT id FROM plandfile WHERE id=(SELECT MAX(id) FROM plandfile)

You don't need a subquery here. Just use "SELECT MAX(id) FROM plandfile" and you'll get the max id.

SunnySan
11th September 2008, 22:37
thanks all
the final working code

QSqlQuery query;
QString plandfileID;
query.exec("SELECT MAX(id) FROM plandfile");
while (query.next()) {
plandfileID = query.value(0).toString();
}
QMessageBox::about(this, tr("Value of ID"),plandfileID);
where id is the primary key of the table plandfile

if you improve the code please let me know ;)

wysota
11th September 2008, 22:56
Sure. Replace "while" with "if".