sql - How to retrieve generated primary key when row was inserted with QSqlTableModel::insertRecord -
this question pertains qt 4.7.3 on windows postgres.
i'm trying insert row pretty large table via qsqltablemodel
, because (hopefully) saves me trouble of typing out field names, using qsqltablemodel::settable
. ask model record object qsqlrecord row(qsqltablemodel::record);
, , fill data via qsqlrecord::setvalue
. here's code persist row:
const bool insertok = tablemodel.insertrecord(-1, row); if (!insertok || !tablemodel.submitall()) { return -1; } qsqlerror err = tablemodel.lasterror(); if (err.type() != qsqlerror::noerror) { std::cerr << "errormsg " << std::endl; return -1; } const int primarykey = tablemodel.query().lastinsertid().toint();
the above tried, content of tablemodel.query()
giant select, no returning
keyword. lastinsertid()
returns invalid qvariant
. possible have qt provide generated primary key without making additional - fugly - roundtrip database. i'd rather not lock table ensure last 1 created, if can avoid it.
please advise.
"solved" using additional query lastval()
. not sure if that's correct way use qt api. lastval()
safe in transactions.