Android sqlite how to check if a record exists
public static boolean CheckIsDataAlreadyInDBorNot(String TableName,
String dbfield, String fieldValue) {
SQLiteDatabase sqldb = EGLifeStyleApplication.sqLiteDatabase;
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = sqldb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
I hope this is useful to you... This function returns true if record already exists in db. Otherwise returns false.
These are all good answers, however many forget to close the cursor and database. If you don't close the cursor or database you may run in to memory leaks.
Additionally:
You can get an error when searching by String
that contains non alpha/numeric characters. For example: "1a5f9ea3-ec4b-406b-a567-e6927640db40
". Those dashes (-
) will cause an unrecognized token
error. You can overcome this by putting the string in an array. So make it a habit to query like this:
public boolean hasObject(String id) {
SQLiteDatabase db = getWritableDatabase();
String selectString = "SELECT * FROM " + _TABLE + " WHERE " + _ID + " =?";
// Add the String you are searching by here.
// Put it in an array to avoid an unrecognized token error
Cursor cursor = db.rawQuery(selectString, new String[] {id});
boolean hasObject = false;
if(cursor.moveToFirst()){
hasObject = true;
//region if you had multiple records to check for, use this region.
int count = 0;
while(cursor.moveToNext()){
count++;
}
//here, count is records found
Log.d(TAG, String.format("%d records found", count));
//endregion
}
cursor.close(); // Dont forget to close your cursor
db.close(); //AND your Database!
return hasObject;
}
you can also see this:
if (cursor.moveToFirst()) {
// record exists
} else {
// record not found
}
OR
You just check Cursor not null after that why you check count not 0.
So, that you try this...
DBHelper.getReadableDatabase();
Cursor mCursor = db.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE yourKey=? AND yourKey1=?", new String[]{keyValue,keyvalue1});
if (mCursor != null)
{
return true;
/* record exist */
}
else
{
return false;
/* record not exist */
}
Raw queries are more vulnerable to SQL Injection. I will suggest using query()
method instead.
public boolean Exists(String searchItem) {
String[] columns = { COLUMN_NAME };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = { searchItem };
String limit = "1";
Cursor cursor = db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null, limit);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
Source: here