How do I get the result code from SQLException or

2019-07-20 11:56发布

问题:

I'm building an REST API and am working on returning the correct status codes to the client. I have a SQLite database and created one table like this:

CREATE TABLE views(id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(10) UNIQUE NOT NULL, data varchar(10) NOT NULL)

The connection to the database works fine. I am able to add a view entity to the table as well. When I run prepStmnt.execute() to add another view with the same name as the first one i get a SQLException as expected (since name is unique).

Since this method can throw SQLException for many reasons, I want to be able to know when the reason is a constraint violation so I can return HTTP status code 409 Conflict to the client. I tried doing this by printing getErrorCode() and getMessage():

catch(SQLException e)
{
    System.out.println(e.getErrorCode() + ": " + e.getMessage());
}

0: [SQLITE_CONSTRAINT] Abort due to constraint violation (column name is not unique)

As you can see I get the error code 0. According to SQLite documentation result code 0 means OK. https://www.sqlite.org/rescode.html

Instead I should get code 19 for SQLITE_CONSTRAINT. The message seems to be correct but I'd rather not parse the message. In SQLite error codes are a subset of result codes, does JDBC take this into account or are error codes completely different? How can I get the result code from SQLException or the prepared statement?