简体   繁体   中英

How to get the ID from a newly inserted row with QSqlQuery and SQLite?

I have a table T that has an field id , which is an INTEGER PRIMARY KEY AUTOINCREMENT , and a INTEGER field f . With Qt5 I insert a row with the following code:

QSqlQuery insert;
insert.exec("INSERT INTO T (f) VALUES (0)");

But how do I get the id of the newly inserted field?

You have to use the lastInsertId() method of QSqlQuery :

QSqlDatabase db = QSqlDatabase::database();
if(db.driver()->hasFeature(QSqlDriver::LastInsertId)){
    QSqlQuery insert;
    bool res = insert.exec("INSERT INTO T (f) VALUES (0)");
    Q_ASSERT(res);

    QVariant id = insert.lastInsertId();
    Q_ASSERT(id.isValid() && !id.isNull());
    qDebug() << id.toInt();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM