Reputation: 5905
I need to delete the specific record from sqlite. But following code not able to delete it.
Please give me some hint.
public void delete(String Id)
{
try {
db.delete(MySQLiteHelper.TABLE_NAME, "Id=?",
new String[] { Id.toString() });
}
catch(Exception e) { ... }
}
Upvotes: 1
Views: 7929
Reputation: 16196
try {
myDB = myDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
String strFilter = "ID =" + ID;
myDB.delete("Table1, strFilter, null);
myDB.close();
Upvotes: 2
Reputation: 307
You can try the following code to delete the Record in Database
public void deleteRowFromTable(String tableName, String columnName, String keyValue) {
mSQLiteDatabase = getWritableDatabase();//To delete , database should be writable.
String mColumName= columnName + "=?";
String[] whereArgs = new String[]{String.valueOf(keyValue)};
mSQLiteDatabase.delete(tableName, mColumName, whereArgs);
mSQLiteDatabase.close();//This is very important once database operation is done.
}
Upvotes: 0
Reputation: 20936
(UPDATED) You should use:
db.delete(MySQLiteHelper.TABLE_NAME, "Id=?", new String[] { Id });
And actually it's suggested to use not 'Id', but BaseColumns._ID
, which is equal "_id".
EDIT: For the future users.
What is the difference between the following methods:
1. db.delete(MySQLiteHelper.TABLE_NAME, "_id=" + Id, null);
2. db.delete(MySQLiteHelper.TABLE_NAME, "_id=?", new String[] {Id});
3. db.delete(MySQLiteHelper.TABLE_NAME, TABLE.ID_COLUMN_NAME + "=?", new String[] {Id});
I can say that all they work well. The difference between the first and the second method is that in general the second method is quicker than first and safer. Why quicker? Because Android can make a cache of parametrized queries, this parametrized query will be faster after the first time. Android cannot make a cache of the first query. Why safer? It's free of SQL injection.
The difference between the second and the third method is that the id column name is not hardcoded in all queries. You can simply define this field only once and then if the name of the column is changed you need to change it only in one place.
Upvotes: 5
Reputation: 2972
try like this:
public void delete(String Id)
{
try {
db.delete(MySQLiteHelper.TABLE_NAME, "Id="+Id, null);
}
catch(Exception e) { ... }
}
Upvotes: 4
Reputation: 7605
Use this
where
ourDatabase ="your database name"
KEY_ROWID="rowid" of your database
& int l=rowid number of which data you want to delete
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID+"="+l, null);
if you put null instead of KEY_ROWID+"="+l than it delete all data
Upvotes: 1
Reputation: 72636
I think that you can execute a simple DELETE SQL Query like :
"DELETE FROM tablename WHERE id = ?"
and pass the id value as a parameter to that query ...
Upvotes: 1