5

我想从表中删除与数组中的 id 匹配的所有行。我可以通过以下两种方法中的任何一种来做到这一点(两种方法都有效)。你能建议哪一个更好吗?

方法一:

public void deleteRec(String[] ids) { //ids is an array
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME, KEY_ID+" IN (" + new String(new char[ids.length-1]).replace("\0", "?,") + "?)", ids);
        db.close();
    }

方法二:

public void deleteRec(String[] ids) { //ids is an array
        String allid = TextUtils.join(", ", ids);
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL(String.format("DELETE FROM "+TABLE_NAME+" WHERE "+KEY_ID+" IN (%s);", allid));
       db.close();
    }
4

5 回答 5

6

忘记第二种方法吧!

ids都是来自数字的字符串(否则 SQL 会失败),但对于通用字符串数据,将数据传递到 SQL 语句绝不是一个好主意。使您的应用程序易受 SQL 注入攻击:

String.format("DELETE FROM t WHERE ID='%s', "1' AND 1=1 --")
// = "DELETE FROM t WHERE ID='1' AND 1=1 --'" => would delete all data!

并且可能会使您的 SQL 语句失败:

String.format("DELETE FROM t WHERE v='%s', "It's me!")
// = "DELETE FROM t WHERE v='It's me!'" => syntactically incorrect (quote not escaped)!

编辑:作为ids字符串数组提供并且可能KEY_ID引用一INT列,方法 1 应适用于:

db.delete(TABLE_NAME, "CAST("+KEY_ID+" AS TEXT) IN (" + new String(new char[ids.length-1]).replace("\0", "?,") + "?)", ids);
于 2013-11-08T10:47:42.643 回答
5

试试这个也许对你有帮助:

String[] Ids = ......; //Array of Ids you wish to delete.
String whereClause = String.format(COL_NAME + " in (%s)", new Object[] { TextUtils.join(",", Collections.nCopies(Ids.length, "?")) });
db.delete(TABLE_NAME, whereClause, Ids);
于 2014-05-20T06:52:42.303 回答
0

阅读此文档,它说您不应将 execSQL 与 INSERT、DELETE、UPDATE 或 SELECT 一起使用,因为它可能存在潜在的安全风险。我仍然相信第一个性能更好。

于 2013-11-08T09:28:32.137 回答
-1

我用这个:

String[] Ids = new String[]{"1", "2", "3"};
mContext.getContentResolver().delete(CONTENT_URI, ID + " IN (?, ?, ?)",Ids);

多?工作。

于 2019-05-22T09:16:38.757 回答
-7

尝试这个

public void deleteRec(String[] ids) { //ids is an array
    SQLiteDatabase db = this.getWritableDatabase();
    for (int i = 0; i < ids.length; i++) {
        //Your code for delete
    }
    db.close();
}
于 2013-11-08T09:45:22.683 回答