Java Android Room @Delete 带参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47538857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:38:37  来源:igfitidea点击:

Android Room @Delete with parameters

javaandroidsqlandroid-room

提问by Hyman

I know I can't use DELETEin a query (that is a shame by the way), I will get the following error:

我知道我不能DELETE在查询中使用(顺便说一句,这是一种耻辱),我会收到以下错误:

<i>Error:error: Observable query return type (LiveData, Flowable etc) can only be used with SELECT queries that directly or indirectly (via @Relation, for example) access at least one table.</i>

But I can't use @Delete(WHERE... xxx)So how do I delete a specific row by a parameter?

但我不能使用@Delete(WHERE... xxx)那么如何通过参数删除特定行呢?

采纳答案by Awais

The beauty of room is, we play with the objects. As per requirement you can use for kotlin:

房间的美妙之处在于,我们可以玩弄物体。根据要求,您可以用于 kotlin:

@Delete
fun delete(model: LanguageModel)

for Java:

对于 Java:

@Delete
void delete(LanguageModel model)

it will delete the exact object which is stored in the db with the same values. LanguageModel is my model class and it works perfectly.

它将删除存储在具有相同值的数据库中的确切对象。LanguageModel 是我的模型类,它工作得很好。

回答by Maragues

Actually, you can use @Queryto perform a delete.

实际上,您可以使用@Query来执行删除。

@Query("DELETE FROM users WHERE user_id = :userId")
abstract void deleteByUserId(long userId);

Extracted from Query javadoc:

查询 javadoc 中提取:

UPDATE or DELETE queries can return void or int. If it is an int, the value is the number of rows affected by this query.

UPDATE 或 DELETE 查询可以返回 void 或 int。如果是 int,则该值是受此查询影响的行数。

回答by Faxriddin Abdullayev

You can use below method to delete by ID

您可以使用以下方法按 ID 删除

@Query("DELETE FROM yourDB WHERE id = :id")
void deleteById();

for delete all rows

删除所有行

@Query("DELETE FROM yourDB")
void delete();