QSqlQuery::execute after an insert returns always failure due to UNIQUE constraint validation. Double insertion while using QSqlQuery
-
Issue
The following code block return failure due to UNIQUE constraint.QString query = QString("INSERT INTO UsedStID(StID,UsedID)VALUES(%1,%2)").arg(createdID).arg(stID); QSqlQuery queryExecuter(query); if(!queryExecuter.exec()) { qDebug() << query <<"____" <<queryExecuter.lastError(); }
Solution
Instead of following line :QSqlQuery queryExecuter(query);
Use like:
QSqlQuery queryExecuter; queryExecuter.exec(query);
Reason
The reason for this issue is, when you are passing a query string to the constructor it will execute this query and return resulting query object that contains data fetched from the DB (inserting result/error string/real data ifselect is used). Please see an example here http://doc.qt.io/qt-5/qsqlquery.html#details
This code snippet:QSqlQuery query("SELECT country FROM artist"); while (query.next()) { QString country = query.value(0).toString(); doSomething(country); }
will fetch the data from the artist table and creates a query object from which the one can retrieve data. It is small thing, but it is not mentioned in documentation.
Note: - This is created as per the communication Dmitry who is a Qt support engineer.
-
Hi,
More precisely you are executing the query twice hence the error since you have a unique constraint in your table.
-
Hi,
More precisely you are executing the query twice hence the error since you have a unique constraint in your table.
@SGaist
Yes. That is the conclusion.