qtqsqldatabase

How can I catch a unique constraint violation through QSqlDatabase?


I have a Qt application, using QSqlDatabase, and I need to take a different action on a unique key constraint violation as opposed to any other type of error.

Currently, the backend database is SQLite, if that matters. However, management is talking about switching to MS SQL Server, so if the solution is database-specific, I'll need one for both.


Solution

  • You can use a QSqlQuery::lastError method to check an error occured while INSERT or UPDATE query execution. It returns QSqlError, which has a nativeErrorCode method. I'm not sure, if it contains only a numeric value or a full error description.

    In common, according to documentation SQLite should return 2067 error, however SQL Server has a different error codes 2601 and 2627, those are table key constraint specific.

    So, you should check, if the string value of QSqlError::nativeErrorCode contains a database engine specific error code.