"Solved" by using an additional query for LASTVAL()
. Not sure if that's the correct way to use the Qt API. LASTVAL()
is safe in transactions.
How to retrieve generated primary key when row was inserted with QSqlTableModel::insertRecord
-
13-04-2022 - |
Pergunta
This question pertains to Qt 4.7.3 on Windows with Postgres.
I'm trying to insert a row into a pretty large table via QSqlTableModel
, because this (hopefully) saves me the trouble of typing out the field names, by using QSqlTableModel::setTable
. I ask the model for a record object with QSqlRecord row(QSqlTableModel::record);
, and fill this with data via the QSqlRecord::setValue
. Here's the code to persist the 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 is what I tried, but the content of tableModel.query()
is a giant select, with no RETURNING
keyword. lastInsertId()
returns an invalid QVariant
. Is it possible to have Qt provide the generated primary key without making an additional - fugly - roundtrip to the database. I'd rather not lock the table to ensure the last is actually the one I created, if I can avoid it.
Please advise.
Solução