Ravi
Ravi

Reputation: 95

Insert only if the value does not exist in sqlite data base otherwise overwrite

I had created sqlite database,What I want to do is that when user enter value then i want to check that the value is already exist if value already exist then UPDATE otherwise INSERT that value, I had tried is...

public long insertDataCat(String id,String cat)
{
 try {
            SQLiteDatabase db;
            db = this.getWritableDatabase(); // Write Data


           ContentValues Val = new ContentValues();
           Val.put("IDD", id);
           Val.put("Categoryy", cat);

            long rows = db.insert(TABLE_CATEGARY_MASTER, null, Val);

            db.close();
            return rows; // return rows inserted.

         } catch (Exception e) {
            return -1;
         }

 }

Upvotes: 1

Views: 3187

Answers (1)

PLP
PLP

Reputation: 714

First you get the cursor count of table if any record found in the table mean it's return the cursor count 1 otherwise return zero.If cursor count one mean you perform UPDATE Operation otherwise Perform Insert Operation.

 public long insertDataCat(String id,String cat)
    {
     try {
                SQLiteDatabase db;
                db = this.getWritableDatabase(); // Write Data


               ContentValues Val = new ContentValues();
               Val.put("IDD", id);
               Val.put("Categoryy", cat);
               String selectQuery = "select * from TABLE_CATEGARY_MASTER";
               Cursor cursor = db.rawQuery(selectQuery, null);`
              if(cursor.getCount()==1)
              {
                //execute update query here
             long updaterow=db.update(TABLE_CATEGARY_MASTER,val);
                return updaterow; // return rows inserted.
              }
              else
              {
                 //Perform the insert query
                 long rows = db.insert(TABLE_CATEGARY_MASTER, null, Val);
                 return rows; // return rows inserted.
              }

                db.close();


             } catch (Exception e) {
                return -1;
             }

 }

Upvotes: 2

Related Questions