3

我的数据库中有几列被注释为 uniqueCombo=true

@DatabaseField(columnName = "COL1", uniqueCombo = true)
private Double col1;

@DatabaseField(columnName = "COL2", uniqueCombo = true)
private Double col2;

根据 ormlite 文档,这两个字段的组合在表中应该是唯一的。为了测试这一点,我特意添加了相同的字段。我确实收到了 SQLException,但不确定如何处理此异常并要求用户进行更改。

try {
        mydao.create(myInfo);

     } catch (SQLException e) {
        // TODO Auto-generated catch block

       e.printStackTrace();
       /* Need to uniquely identify constraint failed error here
        * and ask user to make suitable change */
     }

知道如何实现这一点。

- 更新 - -

SQLException getErrorCode 和 getSQLState 分别返回 0 和 null。

Logcat 堆栈跟踪:

Caused by: android.database.sqlite.SQLiteConstraintException: column NAME is not unique (code 19)
01-31 22:15:14.042: W/System.err(2586):         at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
01-31 22:15:14.042: W/System.err(2586):         at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
01-31 22:15:14.042: W/System.err(2586):         at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
01-31 22:15:14.042: W/System.err(2586):         at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
01-31 22:15:14.042: W/System.err(2586):         at com.j256.ormlite.android.AndroidDatabaseConnection.insert(AndroidDatabaseConnection.java:122)
01-31 22:15:14.042: W/System.err(2586):         ... 15 more
4

2 回答 2

1

我确实收到了 SQLException,但不确定如何处理此异常并要求用户进行更改。

您当然可以捕获异常并查看它是否存在,instanceof SQLiteConstraintException但我总是讨厌将异常视为常见事件。

我要做的是对用户的输入进行查询,以查看是否存在MyInfo具有相同字段的现有对象。类似于以下内容:

QueryBuilder<MyInfo, Integer> qb = mydao.queryBuilder();
qb.where().eq("COL1", myInfo.col1).and().eq("COL2", myInfo.col2);
if (qb.queryForFirst() != null) {
   // tell the user to enter unique values
}
于 2013-02-01T14:22:44.330 回答
0

这不是最好的方法,但这可以帮助某些人......

try {
        //insert to ORMLite
} catch (SQLException e) {
        validateException(e);
}

在 validateException 方法中:

private void validateException(SQLException e) {
        try{
            if (e.getCause() == null)
                throw e;
            if (e.getCause().getCause() == null)
                throw e;
            if (e.getCause().getCause() instanceof SQLiteConstraintException)
                Log.d("Test", "Ignoring duplicate");
            else
                throw e;
        }catch(SQLException e1){
            //exception thrown by e;
        }
    }
于 2015-03-17T21:12:20.213 回答