8

I am trying to query my database based on a specific id.

String sql = "SELECT * FROM mash WHERE recipe_id = '" + id + "'";
Cursor data = database.rawQuery(sql, null);

If this is the first time the activity has been run, the table WILL exist along with the id column, but there will not be a record with the specific id. How can I check if that specific record exists and if it does not, add it? I have found lots of into regarding checking if a specific column exists, but nothing about checking if a specific record exists.

So far I have tried getting the id column index and checking to see if it returns -1, but it actually is returning 1 for some reason. What can I use in an if statement to verify that the id column has not yet been created?

aromero
  • 25,681
  • 6
  • 57
  • 79
ryandlf
  • 27,155
  • 37
  • 106
  • 162

2 Answers2

19
if (cursor.moveToFirst()) {
    // record exists
} else {
    // record not found
}
aromero
  • 25,681
  • 6
  • 57
  • 79
0

My Code is:

public void addContact(String a, String b, String c, String d, SQLiteDatabase db)
    {
        //cursor is use to check if data is availble then show row is exist if not then execute insert query.
        Cursor mCursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS + " WHERE    email=? ", new String[]{b});

        if (mCursor.moveToFirst())
        {
            value=false;
            Toast.makeText(context,"Email alreay exist please enter anothe email id",Toast.LENGTH_LONG).show();
        }
        else
        {
            ContentValues values = new ContentValues();

            values.put(Database_Handler.NAME, a); // Contact Name
            values.put(Database_Handler.EMAIL, b);
            values.put(Database_Handler.PASSWORD, c);
            values.put(Database_Handler.NUMBER, d);

            db.insert(Database_Handler.TABLE_CONTACTS, null, values);
            Log.e("DATABASE OPERATION", "One row is insert");

            Toast.makeText(context,"Data insert Sucessfully",Toast.LENGTH_SHORT).show();
            db.close();
            value=true;

        }
    }
Abhinav Singh Maurya
  • 3,313
  • 8
  • 33
  • 51
Mohd Sakib Syed
  • 1,679
  • 1
  • 25
  • 42