How do I get the result code from SQLException or PreparedStatement with SQLite

若如初见. 提交于 2019-12-24 03:23:53

问题


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?

来源:https://stackoverflow.com/questions/29079582/how-do-i-get-the-result-code-from-sqlexception-or-preparedstatement-with-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!