首页 > 解决方案 > 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 以便批量删除行?我没有找到任何其他解决方案。请看一下并发表评论。

标签: androidsqlitekotlin

解决方案


您的查询看起来有点像:

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)

推荐阅读