Android SQL: check if a record exists in the database

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 run of this operation, the table will exist along with the id column, but there will be no record with a specific identifier. How can I check if this particular entry exists, and if not, add it? I have found many questions regarding checking for the presence of a specific column, but nothing is checking if a specific record exists.

So far, I have been trying to get the index of the id column and checking if it returns -1, but for some reason it really returns 1. What can I use in the if statement to verify that the id column has not been created yet?

+7
source share
2 answers
 if (cursor.moveToFirst()) { // record exists } else { // record not found } 
+19
source

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; } } 
0
source

All Articles