Reputation: 24324
Inserting data to SQLite table with constraint failure
I'm trying to insert data into SQLite table on Android. _id
is primary key of the table and I am inserting a row using this method:
public void addSomeData(int id, String datetime) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, id);
contentValues.put(KEY_DATETIME, datetime);
mDb.insert(TABLE, null, contentValues);
}
The problem I get is that sometimes primary key constraint is validated and I would like to use something like INSERT IF NOT EXISTS
, but preferably something that would work with ContentValues
. What are my options? I understand that insertOrThrow()
and insertWithOnConflict()
methods only return different values, or should I use one of these methods?
Upvotes: 0
Views: 158
Reputation: 11151
Use insertWithOnConflict()
with CONFLICT_IGNORE
.
Will return ROWID/primary key of new or existing row, -1 on any error.
Upvotes: 1
Reputation: 2355
to do so you could simply query the db to see if a row with that key exists and insert the new row only if the query returns no data.
Upvotes: 0
Reputation: 5893
In my case "constraint failure" happened because of I had some tables which are depended on each other. As for the "insert if not exist", you can query with this id and you check if the cursor's count is bigger than zero. Check the method I'm already using in my app.
public boolean isRowExists(long rowId) {
Cursor cursor = database.query(this.tableName, this.columns, DBSQLiteHelper.COLUMN_ID + " = ? ", new String[] { "" + rowId }, null, null, null);
int numOfRows = cursor.getCount();
cursor.close();
return (numOfRows > 0) ? true : false;
}
Upvotes: 0