android - Kotlin / SQLite delete() 批处理问题
问题描述
我想根据 ID 列从 SQLite 中批量删除多个项目。
我所拥有的是一个 HashMap,其中包含字段之一是 pID(DB 中的唯一 ID)的对象。
所以,这是我的代码:
/*
Delete rows from DB
*/
val selection = "${BaseColumns._ID} = ?"
// Create a list of product ID's to delete
val dbDeletor = dbHelper.writableDatabase
// Temp array to store ID's in String format
val tempIDs = ArrayList<String>()
// Loop through array of items to be deleted
for(i in ProductsRecyclerAdapter.productsToDeleteArray)
tempIDs.add(i.value.pID.toString())
// Perform deletion in DB
val deletedRowsCount = dbDeletor.delete(ProductsEntry.TABLE_NAME, selection, tempIDs.toTypedArray())
// Show snackbar with count of deleted items
Snackbar.make(mainCoordinatorLayout, "Products deleted: $deletedRowsCount", Snackbar.LENGTH_SHORT).show()
当我只删除 1 个项目时一切正常,但如果 tempIDs 数组包含 2 个或更多,我将收到以下异常:
绑定参数太多。提供了 3 个参数,但该语句需要 1 个参数。
也许原因是我将 Long 类型的 pID 转换为 String 以便批量删除行?我没有找到任何其他解决方案。请看一下并发表评论。
解决方案
您的查询看起来有点像:
DELETE FROM ProductsEntry.TABLE_NAME WHERE BaseColumns._ID = ?
只有 1 个参数?
,但您传递了 3 个值(ID)。您想改用IN
语句,并打印以逗号分隔的参数:
// IN instead of equal to compare multiple values
val selection = "${BaseColumns._ID} IN (?)"
// your code to obtain IDs here
// .....
// combine all values into single string, ie. 1, 2, 3, 4 and wrap it as an array
val selectionArg = arrayOf(tempIDs.joinToString())
// Perform deletion in DB
val deletedRowsCount = dbDeletor.delete(ProductsEntry.TABLE_NAME, selection, selectionArg)
推荐阅读
- java - 启动 Spring Boot 应用程序时如何解决 Gson builder 错误
- javascript - JavaScript 的 onscroll() 函数有问题
- flutter - 如何创建浏览量重叠效果?
- javascript - 如何使用 JQuery 将段落添加到 Bootstrap 模态正文?
- python - 根据 pyspark 中的条件填充新列
- java - java.lang.RuntimeException:无法实例化活动 ComponentInfo{.UpdateProfileFragment 无法转换为 android.app.Activity
- asp.net-mvc - Asp Mvc:使用存储在数据库中的图像设置内联 css background-image:url
- ruby-on-rails - 我怎样才能爱上heroku H13?
- php - Laravel 工厂逻辑
- html - 如何在 div 中应用填充和边框(带有多个标签)?