当字符串包含“ - ”时,无法删除sqlite中的特定行

时间:2013-09-14 16:20:27

标签: android

我有简单的列表视图,显示名称和编号(此数据实际来自数据库)。当我尝试删除其工作正常(数字字段为“123456”)但问题是无法删除一些列表项目,其数字字段为“888-888-00”

这里添加了我的代码...... Plesae帮助我....,

DatabaseHelpher.java

private static final String KEY_NAME = "name";
private static final String KEY_NUMBER = "number";

public void deleteContacts(String name, String number){
    //Raw Query wont work for Deletion
    db = this.getWritableDatabase();
    System.out.println("deleted number: "+number+"name: "+name);
    String deleteQuery = "Delete from "+CONTACTS_TABLE_NAME+" where "+KEY_NUMBER+" = "+number;
    //db.rawQuery("Delete from "+CONTACTS_TABLE_NAME+" where "+KEY_NUMBER+" = "+number, null);
    db.execSQL(deleteQuery);
    db.close();
}

MainActivity.java

在oncreate()方法中包含,

selectedListView.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {

            final HashMap<String, String> toDelete = (HashMap<String, String>) selectedListView.getItemAtPosition(position);

            AlertDialog.Builder deleteDialog = new AlertDialog.Builder(MainActivity.this);
            deleteDialog.setTitle("Confirm Delete...");
            deleteDialog.setMessage("Are you sure you want delete this '"+toDelete.get("name")+"' Contact?");

            deleteDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {

                    dataBaseHelpher.deleteContacts(toDelete.get("name"), toDelete.get("number"));
                    dialog.dismiss();
                    updateList();
                }
            });
            deleteDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();
                }
            });
            deleteDialog.show();
        }
    });

2 个答案:

答案 0 :(得分:2)

你需要用引号'原因'来包围你的号码'888-888-888'是一个不是整数的字符串。

String deleteQuery = "delete from " + CONTACTS_TABLE_NAME + " where " + KEY_NUMBER + " = '" + number + "'";

最好使用像这样的预备语句。

SQLiteDatabase db = dbHelper.getWritableDatabase();
SQLiteStatement stmt = db.compileStatement("delete from ? where ? = ?");
stmt.bindString(1, CONTACTS_TABLE_NAME);
stmt.bindString(2, KEY_NUMBER );
stmt.bindString(3, number);
stmt.execute();

答案 1 :(得分:1)

试试这段代码 -

db.delete("Your Table Name", "KEY_NUMBER = " + number, null);