SQLiteConstraintException:更新行时列id不是唯一(代码19)异常

ojo*_*ifu 1 sqlite android android-database

我在我的数据库中有一个表,当添加新记录时,我正在检查记录是否存在使用id.如果它存在,我想更新记录,如果它没有添加新记录.但我得到了例外:

2006年至2259年/?E/SQLiteDatabase:插入错误id = 080333 phone = 080333 total_owed = 15050.0 total_debts = 0 name = Alison Jones android.database.sqlite.SQLiteConstraintException:列id不唯一(代码19)

这是检查记录是否存在的方法:

 public boolean checkIfExists(String tableName, String value) {

    SQLiteDatabase database = this.getReadableDatabase();

    String Query = "Select * from " + tableName + " where " + DEBTOR_ID + " = " + value;
    Cursor cursor = database.rawQuery(Query, null);
    if(cursor.getCount() <= 0){
        cursor.close();
        return false;
    }
    cursor.close();
    return true;

}
Run Code Online (Sandbox Code Playgroud)

它在这里被使用:

            debtor.setDebtorName(params[0]);
            debtor.setPhoneNumber(params[1]);
            debtor.setTotalAmountOwed(Double.parseDouble(params[6]));
            debtor.setTotalDebts(0);

            if (databaseHandler.checkIfExists(DebtDatabaseHandler.DEBTOR_TABLE_NAME, params[1])) {
                Log.d("NewDebtFragment", "Record already exist");
                databaseHandler.updateRecord(2, debtor.getTotalAmountOwed() + 50000);
            } else {
                debtorId = databaseHandler.addDebtor(debtor);
            }
Run Code Online (Sandbox Code Playgroud)

由于这是一个冲突问题,显然对现有记录的检查不起作用.我不知道这是因为代码似乎没问题(?)

这是创建表的方式:

String CREATE_DEBTOR_TABLE = "CREATE TABLE  " + DEBTOR_TABLE_NAME + " ( " +
            DEBTOR_ID + " TEXT PRIMARY KEY, " +
            DEBTOR_NAME + " TEXT, " +
            PHONE_NUMBER + " TEXT, "+
            TOTAL_DEBTS + " INTEGER, " +
            TOTAL_OWED + " INTEGER) ";
Run Code Online (Sandbox Code Playgroud)

updateRecord方法:

 public void updateRecord(int newTotalDebt, double newTotalOwed) {

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(TOTAL_DEBTS, newTotalDebt);
    contentValues.put(TOTAL_OWED, newTotalOwed);

    db.update(DEBTOR_TABLE_NAME, contentValues, DEBTOR_ID, null);


}
Run Code Online (Sandbox Code Playgroud)

Kar*_*eek 8

用以下内容替换您的查询

 String Query = "Select * from " + tableName + " where " + DEBTOR_ID + " = '" + value+"'";
Run Code Online (Sandbox Code Playgroud)

因为选择value是字符串,所以必须用单引号括起来.

更新:
您可以使用简单的单行替换所有这些内容,而不是编写整串代码来检查记录是否退出,如果退出然后更新该记录.

database.insertWithOnConflict(table,null,values,SQLiteDatabase.CONFLICT_REPLACE);
Run Code Online (Sandbox Code Playgroud)

它将在内部处理异常,CONFLICT_REPLACE它指定当发生UNIQUE约束违规时,在插入或更新当前行之前,将删除导致违反约束的预先存在的行.