开发者

Android SQLiteDatabase.delete method wouldn't delete using where args

Watch how i call the db.delete method; if I do the following a record is successfully deleted:

public void deteleProfile(Long id) throws SQLException {
        SQLiteDatabase db = helper.getWritableDatabase();
        Integer i = db.delete(ProlificDatabase.TABLE, "_id=?", new String[] {id.toString()});
        Log.d(TAG, i + " records deleted where id is " + id);

however if I do this:

public void deteleProfile(Long id) throws SQLException {
        SQLiteDatabase db = helper.getWritableDatabase();
        Integer i = db.delete(ProlificDatabase.TABLE, "?=?", new String[] {BaseColumns._ID,id.toString()});
        Log.d(TAG, i + " records deleted where id is " + id);

no records are deleted. also no exceptions or warnings are raised to say something has gone wrong.

in case you didn't catch it, the difference between the two calls were:

..."_id=?", new String[] {id.toString()});

vs

..."?=?", new String[] {BaseColumns._ID,id.toString()});

documentation for BaseColumns._ID is:

public static final String _ID with a Constant Value: "_id"

The latter way se开发者_如何转开发ems to make for neater code, but why doesn't it work?

EDIT: I suspect the whereargs parameter only applies to the right side of an expression.

Can someone confirm this?


the Strings you provide in whereArgs are escaped and enclosed in '

"?=?", new String[] {BaseColumns._ID,id.toString()});

translates to

'_id'='1234'

which is valid SQLite syntax but does string comparison instead of a table lookup. Since "_id" is not the same String as "1234" (or any other number) the expression will always evaluate to false and nothing will get deleted.

What you should use is the following syntax

Integer i = db.delete(ProlificDatabase.TABLE, BaseColumns._ID + "=?", new String[] {id.toString()});


  public void deteleProfile(Long id) throws SQLException 
  {
     SQLiteDatabase db = helper.getWritableDatabase();
     Integer i = db.delete(ProlificDatabase.TABLE, "_id=" + id, null);
     Log.d(TAG, i + " records deleted where id is " + id);
  }

and this link is a good example of SQLite database of android.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜