我的数据库中有一个表,当添加新记录时,我正在使用 id 检查记录是否存在。如果存在,我想更新记录,如果它不添加新记录。但我得到了例外:
2006-2259/? E/SQLiteDatabase:错误插入 id=080333 phone=080333 total_owed=15050.0 total_debts=0 name=Alison Jones android.database.sqlite.SQLiteConstraintException: column id is not unique (code 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;
}
它在这里被使用:
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);
}
由于这是一个冲突问题,显然对现有记录的检查不起作用。我不知道为什么这是因为代码看起来很好(?)
这是创建表的方式:
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) ";
和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);
}