我有一个表在我的数据库,添加新的记录,当我检查是否存在记录使用id.If它,我想更新的记录,如果它不添加一个新的记录。 但我得到的例外:
2006年至2259年/? E / SQLiteDatabase:错误插入ID = 080333电话= 080333 total_owed = 15050.0 total_debts = 0名=艾利森琼斯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;
}
并且它正在这里使用:
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);
}
由于这是一个矛盾的问题,显然对现有记录的检查是不是working.I不为什么,这是因为代码似乎罚款(?)
这是怎么了创建表:
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);
}