0

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.

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It turns out that SQLite returns code "19" for duplicate unique keys. Thanks for the help!
In PyQt6 with bundled SQLite version 3.46.1, it returns "2067" (as string).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.