Home > database >  How can I catch a unique constraint violation through QT's QSqlDatabase interface?
How can I catch a unique constraint violation through QT's QSqlDatabase interface?

Time:06-28

The title says it all, really. I have a QT application, using the QSqlDatabase interface, 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.

CodePudding user response:

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.

  • Related