问题
I have a table in my database, when adding new record I am checking if the record exists using the id.If it does, I want to update the record and if it doesn't add a new record. But am getting the exception:
2006-2259/? E/SQLiteDatabase﹕ Error inserting 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)
This is the method that checks if a record exists:
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;
}
and it is being used here:
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);
}
Since this is a conflict issue, obviously the check for existing record isn't working.I don't why this is because the code seem fine (?)
This is how am creating the table:
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) ";
and the updateRecord
method:
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);
}
回答1:
Replace your query with the below
String Query = "Select * from " + tableName + " where " + DEBTOR_ID + " = '" + value+"'";
since selection value
is string , it must be enclosed in single quote.
Updated :
Instead of writing whole bunch code for checking whether record exits or not if exits then udpating that record, you can replace all these things with a simple single line.
database.insertWithOnConflict(table,null,values,SQLiteDatabase.CONFLICT_REPLACE);
It will internally handles the exception, CONFLICT_REPLACE
it specifies that When a UNIQUE constraint violation occurs, the pre-existing rows that are causing the constraint violation are removed prior to inserting or updating the current row.
来源:https://stackoverflow.com/questions/30706305/sqliteconstraintexception-column-id-is-not-unique-code-19-exception-when-upda