BRD*_*oid 2 android suspend kotlin android-database android-room
我正在将行插入 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
)
Run Code Online (Sandbox Code Playgroud)
当我插入一行时,响应是 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
}
Run Code Online (Sandbox Code Playgroud)
注意:我得到的结果是 1,2,3 等,这应该是 rowId。
请建议这种方法是否正确?基本上,如果插入不成功,我想阻止用户进一步继续
感谢您的建议和输入 R
根据此处的文档Room Dao @Insert
如果@Insert方法只接收1个参数,它可以返回一个long,这是插入项的新rowId。如果参数是数组或集合,则应返回 long[] 或 List。
最重要的是,用 @Insert 注释注释的方法可以返回:
如果返回值为 -1 或负数,则根据docs认为操作失败。
编辑回答@patrick.elmquist评论
从房间生成的代码。EntityInsertionAdapter和SupportSQLiteStatement
/**
* 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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3068 次 |
| 最近记录: |