You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Room查询使用枚举判断报错,求语句正确性排查与解决

问题分析与解决方案

错误原因

你的@Query语句直接在SQL中使用Kotlin枚举常量ETranslateState.COMPLETED,但Room通过TypeConverter将枚举类型转换为**整数(ordinal值)**存储到SQLite数据库中,SQLite无法识别Kotlin的枚举语法,因此报错“no such column: ETranslateState.COMPLETED”。

正确解决方案(推荐)

使用Room的参数绑定机制,让Room自动调用TypeConverter将枚举常量转换为数据库存储的数值,既安全又避免硬编码。

修改RecordDao代码如下:

@Dao
interface RecordDao {  
    @Query("SELECT * FROM info_table where translateState != :completedState ORDER BY createdDate desc")
    fun listAllExceptIncompleted(completedState: ETranslateState = ETranslateState.COMPLETED): Flow<List<RecordEntity>>
}

补充说明

  1. 方法参数默认值ETranslateState.COMPLETED可以让调用方无需手动传入参数,简化使用
  2. 确保你的Room数据库类已经添加了TypeConverter引用(如果尚未添加):
@Database(entities = [RecordEntity::class], version = 1)
@TypeConverters(DBConvert::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun recordDao(): RecordDao
}

可选方案(不推荐)

如果不想使用参数绑定,可以直接使用枚举对应的ordinal值(COMPLETED是第4个枚举项,ordinal值为3),但这种方式硬编码数值,后续枚举顺序修改会导致逻辑错误:

@Dao
interface RecordDao {  
    @Query("SELECT * FROM info_table where translateState != 3 ORDER BY createdDate desc")
    fun listAllExceptIncompleted(): Flow<List<RecordEntity>>
}

内容的提问来源于stack exchange,提问作者HelloCW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 14:40:10