如何在SQLite中删除有多个where args的记录?[英] How to delete rows in SQLite with multiple where args?

本文是小编为大家收集整理的关于如何在SQLite中删除有多个where args的记录?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我想删除满足多种条件的行的行.

例如,我通过ID列表,我想用这些IDs删除所有行(ID是唯一的).

这将是:

String[] ids = {"0", "1", "2", "3",...};
database.delete("rows" , "id=? OR id=? OR id=? OR id=? OR ..." , ids );

有什么方法可以在没有多个OR的情况下进行紧凑?

推荐答案

您可以通过db.execSQL方法和关键字中的SQL的完成.例如:

String args = TextUtils.join(", ", ids);

db.execSQL(String.format("DELETE FROM rows WHERE ids IN (%s);", args));

其他推荐答案

您要使用的是IN子句,类似(带4个IDS);

database.delete("rows", "id IN (?, ?, ?, ?)", ids );

应要求,这是(一个例子)您如何动态地做;

database.delete("rows", 
    "id IN (" + new String(new char[ids.length-1]).replace("\0", "?,") + "?)", 
    ids);

其他推荐答案

Android官方文档告诉在这里使用ExecSQL不是删除记录的正确方法.

我想建议以下简单方法.使用提供的delete() api.

String[] idArray = new String[] {"1", "2", "3"};
String idsCSV = TextUtils.join(",", idArray);
SQLiteDatabase db = getWritableDatabase();
if (db != null) {
    db.delete("table_name", "id IN (" + idsCSV + ")", null);
    db.close();
}

本文地址:https://www.itbaoku.cn/post/597585.html

问题描述

I want to delete rows which satisfy any of multiple conditions.

For example, I pass a list of IDs, and I want to delete all rows with these IDs (IDs are unique).

This would be:

String[] ids = {"0", "1", "2", "3",...};
database.delete("rows" , "id=? OR id=? OR id=? OR id=? OR ..." , ids );

Is there any way to do it compact without multiple OR?

推荐答案

You may get it done through db.execSQL method and SQL's IN keyword. For example:

String args = TextUtils.join(", ", ids);

db.execSQL(String.format("DELETE FROM rows WHERE ids IN (%s);", args));

其他推荐答案

What you want to use is an IN clause, something like (with 4 IDs);

database.delete("rows", "id IN (?, ?, ?, ?)", ids );

Upon request, this is (one example of) how you can do it dynamically;

database.delete("rows", 
    "id IN (" + new String(new char[ids.length-1]).replace("\0", "?,") + "?)", 
    ids);

其他推荐答案

Android official documentation tells here that using execSQL is not the proper way to delete records.

I would like to suggest the following simple method. Using provided delete() api.

String[] idArray = new String[] {"1", "2", "3"};
String idsCSV = TextUtils.join(",", idArray);
SQLiteDatabase db = getWritableDatabase();
if (db != null) {
    db.delete("table_name", "id IN (" + idsCSV + ")", null);
    db.close();
}