1

Can you please tell me how to get in Qt the last value of column, from database.

I know I can get the last value using while loop, but that is too much work for the program.

depecheSoul
  • 896
  • 1
  • 12
  • 29

3 Answers3

1

You can try QSqlQuery::lastInsertId, just after the insert query (For Postgresql, the query must still be active and the table must contain OIDs).

If it doesn't work and the returned QVariant is invalid, you can try the other Postgresql methods:
postgreSQL function for last inserted ID

Community
  • 1
  • 1
alexisdm
  • 29,448
  • 6
  • 64
  • 99
1

In my case, nothing work what i found in google and here. Finally i found solution. Maybe it's not optimized and pretty but work fine

int SomeClass::get_last_id(QString sequence){
  QSqlQuery query(QString("select currval('%1')").arg(sequence), this->dbh);
  query.next();
  return query.value(0).toInt();
}

Usage with QSqlTableModel:

model->setTable(TABLE_NAME);
model->insertRows(0, 1);
model->setData(model->index(0, parent_domain), _domain);
model->setData(model->index(0, parent_token), _token.mid(0,19).toUpper());
model->setData(model->index(0, parent_name), _name);
model->submitAll();
int id = get_last_id(TABLE_SEQUENCE);
Jerzy Drożdż
  • 438
  • 6
  • 8
0
QSqlQuery sqlQuery;
sqlQuery.prepare("SELECT \"Ime\", \"Prezime\", \"ID\" FROM tabela;");
sqlQuery.exec();
if (sqlQuery.isActive()){
    if (sqlQuery.isSelect()){
        if (sqlQuery.last()){
            QString string=sqlQuery.value(2).toString();
        }
    }
}

Solution

depecheSoul
  • 896
  • 1
  • 12
  • 29
  • That's not a very good solution because the database might have to generate all the rows even if you are only use one of them. If you only want the last row, use `SELECT Ime, Prezime, id from tabela order by id desc limit 1`. – alexisdm Apr 08 '12 at 12:47