I am new to qt. I have created a table in sql, and what I'm trying to do is to give an id whenever user adds data. For the first thing inserted it will be 1, second 2 and so on. So how to check what number was the last one? Should I create
query.prepare(sql statement) or is there other way?
Best How To :
The method you're looking for is
QSqlQuery::lastInsertId(). To quote the documentation:
Returns the object ID of the most recent inserted row if the database supports it. An invalid QVariant will be returned if the query did not insert any value or if the database does not report the id back. If more than one row was touched by the insert, the behavior is undefined.
I can confirm from experience that this functionality is indeed supported for SQLite databases in Qt.
You can convert the variant to a database ID like so:
qint64 insertID = query.lastInsertId().toLongLong();