我需要删除ORMLite数据库中的记录我可以使用id删除记录,如下所示
@Override
public void Delete(int id) throws SQLException {
this.dao.deleteById(id);
}
但是如果我必须从同一个表中删除记录而不是通过id但是通过名称或任何其他字段删除 我想要像
这样的东西public void Deletefromcanteen(String name,MealType mealtype) {
this.dao.deletebyName(name);
}
我应该使用querybuilder写一个查询来删除name = name和mealtype = say(午餐)的记录
我在databasehelper类中尝试过类似的东西
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) {
...
}
}
答案 0 :(得分:72)
deleteBuilder.where().eq("FIELD_NAME", arg);
deleteBuilder.delete();
更新
例如:
//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();
祝你好运!
答案 1 :(得分:0)
要保存构建查询,您可以执行select以查找ID,然后按ID进行删除。如果您已经为此表设置了选择查询,那么Thsi将很简单。
答案 2 :(得分:0)
也可以这样做
DatabaseHelper.getInstance().getDao(YourObject.class).delete(yourObjectInstance);
答案 3 :(得分:0)
如果您使用的是Kotlin,则需要执行类似的操作,因为类型推断目前无法正常使用流畅的语法:
val deleteBuilder = dao.deleteBuilder()
val where = deleteBuilder.where().eq("address", address)
deleteBuilder.setWhere(where)
deleteBuilder.delete()
答案 4 :(得分:0)
如果您已经拥有要删除的对象(或对象列表)的实例,请执行以下操作:
//Get helper
DatabaseHelper helper =
OpenHelperManager.getHelper(App.getContext(), DatabaseHelper.class);
// delete 'em !
helper.getDao(YourObject.class).delete(yourObjectInstance);
如果您没有要删除的实例,或者您想以SQL方式(!):
执行此操作//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", "FIELD_VALUE");
deleteBuilder.delete();
如果您需要更复杂的Where
逻辑,请使用deleteBuilder.where().or()
或deleteBuilder.where().and()
添加更多约束。