SQlite删除具有特定字符串值的所有行

时间:2016-07-07 12:21:28

标签: android sqlite delete-row

此代码仅删除我的表中的单个记录,我想要实现的是,删除具有给定字符串电话值的所有记录。我是SQlite的新手,非常感谢。提前谢谢。

此代码删除单个记录成功:

public void delSmsData(int id){
    String deleteQuery = "DELETE FROM "+TABLE_LO_SMSDATA+" WHERE _id="+id+"";
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL(deleteQuery); //delete single row by ID in a table
    db.execSQL("vacuum");
    db.close();
    Log.e("Debug", "Successful delete of message with id no. " + id);
}

我成功删除了使用此代码的所有记录。感谢那些帮助过的人。

public void delAllSmsByPhone(String phone){
    String deleteQuery = "DELETE FROM "+TABLE_LO_SMSDATA+" WHERE _phone='"+phone+"'";
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL(deleteQuery); 
    db.execSQL("vacuum");
    db.close();
}

这是我的表结构:

String CREATE_LO_SMSDATA_TABLE = "CREATE TABLE "
            +TABLE_LO_SMSDATA+"("
            +KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"
            +KEY_EMAIL+" TEXT,"
            +KEY_TARGETNAME+" TEXT,"
            +KEY_SMSTYPE+" TEXT,"
            +KEY_PHONE+" TEXT,"
            +KEY_CONTACTNAME+" TEXT,"
            +KEY_SMSBODY+" TEXT,"
            +KEY_DATE+" TEXT"+")";
    db.execSQL(CREATE_LO_SMSDATA_TABLE);

1 个答案:

答案 0 :(得分:1)

我完全不了解你。你试过运行代码吗?

  

此代码不是正确的方法

这是绝对正确的方法。 DELETE可以删除任何行数,而不仅仅是一行。它删除WHERE子句为真的所有行。

证明:

sqlite> .tables
sms
sqlite> .schema sms
CREATE TABLE `sms` (
    `_id`   INTEGER PRIMARY KEY AUTOINCREMENT,
    `_phone`    TEXT
);
sqlite> SELECT * FROM sms;
1|+79271234567
2|+79271234567
3|+79213983722
4|+79271234567
5|+78450738422
6|+79271234567
7|+77432739417
8|+74673627246
9|+79271234567
10|+79271234567
sqlite> DELETE FROM sms WHERE _phone='+79271234567';
sqlite> SELECT * FROM sms;
3|+79213983722
5|+78450738422
7|+77432739417
8|+74673627246