检查是否将行插入到会议室数据库中

时间:2020-10-23 11:03:39

标签: android kotlin android-room android-database suspend

我正在将行插入到Room数据库中,我想检查是否已成功插入行。

这是我的道

@Insert()
suspend fun insertOfflineData(offlineData: OfflineData): Long

@Entity
data class OfflineData(
    @PrimaryKey(autoGenerate = true)
    val id: Int = 0,
    @ColumnInfo(name = "request_info_json")
    val requestInfoJson: String
)

当我插入一行时,响应为1,2,3,依此类推。 所以它是返回的id(是吗?)

因此要检查该行是否正确插入。

我可以检查插入的rowId是否大于0,然后将其成功插入数据库。

private suspend fun insertOfflineData(offlineDataRequestInfo: String): Long {
        var result: Long = 0
        result = OfflineDatabaseManager.getInstance(app.applicationContext).insertOfflineData(
            OfflineData(
                0,
                offlineDataRequestInfo
            ))
        if(result > 0 ) {
            //SUCCEFFLULLY INSERTED
        } else {
            //UNSUCCESSFULL
        }
        return result
    }

注意:我得到的结果是1,2,3等,应该是rowId。

请建议这种方法是否正确? 基本上,如果插入不成功,我想阻止用户继续进行操作

感谢您的建议和意见 R

2 个答案:

答案 0 :(得分:1)

根据此处Room Dao @Insert

的文档

如果@Insert方法仅接收1个参数,则它可以返回long,这是插入项的新rowId。如果参数是数组或集合,则应返回long []或List。

最重要的是, 带有@Insert批注的方法可以返回:

  1. 单个插入操作的长值。
  2. 一个long []或Long []或用于多个插入操作的列表。
  3. 如果您不在乎插入的ID,则为空。

如果返回值为-1或负数,则根据docs来考虑操作失败。

编辑回答@ patrick.elmquist评论

来自房间生成的代码。 EntityInsertionAdapterSupportSQLiteStatement

/**
     * Execute this SQL statement and return the ID of the row inserted due to this call.
     * The SQL statement should be an INSERT for this to be a useful call.
     *
     * @return the row ID of the last row inserted, if this insert is successful. -1 otherwise.
     *
     * @throws android.database.SQLException If the SQL string is invalid for
     *         some reason
     */
    long executeInsert();

答案 1 :(得分:-1)

您可以使用this one之类的数据库调试库