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?

2 Answers 2

19
if (cursor.moveToFirst()) {
    // record exists
} else {
    // record not found
}
Sign up to request clarification or add additional context in comments.

Comments

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;

        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.