how to delete a record from ORMLITE?

Sourabh Saldi picture Sourabh Saldi · Aug 24, 2012 · Viewed 22.5k times · Source

I need to delete a record from ORMLite Database I can delete a record by id using as below

@Override
public void Delete(int id) throws SQLException {
    this.dao.deleteById(id);
}

but what if I have to delete a record from same table not by id but by name or any other field I want something like

public void Deletefromcanteen(String name,MealType mealtype) {
    this.dao.deletebyName(name);
}

what query should i write using querybuilder to delete a record where name = name and mealtype = say (lunch)

I tried something like this in my databasehelper class

public  void deletefromcanteen(int id, String mealtype) {
    try {
        Dao<CanteenLog, Integer> canteenDao = getCanteen();
        DeleteBuilder<CanteenLog, Integer> deleteBuilder = canteenDao
                .deleteBuilder();
        deleteBuilder.where().eq("user_id", id).and().eq("meal", mealtype);
        canteenDao.delete(deleteBuilder.prepare());
    } catch (Exception e) {
        ...
    }
}

Answer

Ilya Demidov picture Ilya Demidov · Aug 24, 2012
deleteBuilder.where().eq("FIELD_NAME", arg);
deleteBuilder.delete();

Update:

For example :

//Get helper
DatabaseHelper helper = OpenHelperManager.getHelper(App.getContext(), DatabaseHelper.class);

//get dao
Dao dao = helper.getDao(YOUR_CLASS.class);

//delete elements from table in field by arg
DeleteBuilder<CanteenLog, Integer> deleteBuilder = dao.deleteBuilder();
deleteBuilder.where().eq("FIELD_NAME", arg);
deleteBuilder.delete();

Good luck!