Skip to content Skip to sidebar Skip to footer

Android Sqlite Insert If Not Exists

In my android application I need to save data into database . The values are user's name and DOB details. So before saving the details I need to check whether the data is existing

Solution 1:

Check if row already exist in database or not, and depending on this update or insert your data:

publicLongsaveUser(Some values) {
            long rowId;
            String sql = "SELECT * FROM Data2 WHERE COLUMN_1 = ? AND COLUMN_2 = ?";
            Cursor cursor = getSqLiteDatabase().rawQuery(sql, newString[]{"column_value_1" ,"column_value_2"});
            if (cursor == null || !cursor.moveToFirst()) {
                //Insert new
                rowId = getSqLiteDatabase().insert(Data2, null, yourCV);
            } else {
                //UpdateString clause = "COLUMN_1 = ? AND COLUMN_2 = ?";
                String args[] = {"column_value_1" ,"column_value_2"};
                rowId = getSqLiteDatabase().update(User.DB_KEYS.TABLE.toString(), UserSqlStorage.saveUserCV(user), clause, args);
            }
            closeCursor(cursor);
            return rowId;
        }

Solution 2:

You can use the following approach..

Cursorcursor= db.rawQuery("select id from tblUniqueNumber  WHERE fname = " + fname + " &&     lname =" + lname + " && DOB = "  + DOB, null);

if(cursor.moveToFirst())
{

} else {
  // insert
}

Solution 3:

I always create a saveOrUpdate() method so that it attempts to update, but if no rows where affected, it saves (as it means the data is new)

Post a Comment for "Android Sqlite Insert If Not Exists"