111

This might be a dumb question, but I'm new to SQLite and I can't seem to figure this out. I have 1 table that has columns KEY_ROWID, KEY_NAME, KAY_LATITUDE, and KEY_LONGITUDE. I want the user to be able to select one and delete it; Can anyone give me a direction to start in? My question is in the actual deletion of the row given only its name.

Relevant code:

public class BeaconDatabase {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "beacon_name";
    public static final String KEY_LATITUDE = "beacon_lat";
    public static final String KEY_LONGITUDE = "beacon_lon";

    private static final String DATABASE_NAME ="BeaconDatabase";
    private static final String DATABASE_TABLE ="beaconTable";
    private static final int DATABASE_VERSION = 1;

    private DbHelper helper;
    private final Context context;
    private SQLiteDatabase db;

    public BeaconDatabase(Context context) {
        this.context = context;
    }

    public BeaconDatabase open() {
        helper = new DbHelper(this.context);
        db = helper.getWritableDatabase();
        return this;
    }

    public void close() {
        helper.close();
    }

    public long createEntry(String name, Double lat, Double lon) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_LATITUDE, lat);
        cv.put(KEY_LONGITUDE, lon);
        return db.insert(DATABASE_TABLE, null, cv);
    }

    public void deleteEntry(long row) {

              // Deletes a row given its rowId, but I want to be able to pass
              // in the name of the KEY_NAME and have it delete that row.
              //db.delete(DATABASE_TABLE, KEY_ROWID + "=" + row, null);
    }

    public String getData() {
        String[] columns = { KEY_ROWID, KEY_NAME, KEY_LATITUDE, KEY_LONGITUDE };
        Cursor cursor = db.query(DATABASE_TABLE, columns, null, null, null, null, null);
        String result = "";

        int iRow = cursor.getColumnIndex(KEY_ROWID);
        int iName = cursor.getColumnIndex(KEY_NAME);
        int iLat = cursor.getColumnIndex(KEY_LATITUDE);
        int iLon = cursor.getColumnIndex(KEY_LONGITUDE);

        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            result += cursor.getString(iRow) + ": " + cursor.getString(iName) + " - " + cursor.getDouble(iLat) + " latitude " + cursor.getDouble(iLon) + " longitude\n";
        }

        return result;

    }

    private static class DbHelper extends SQLiteOpenHelper {

        public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " +  DATABASE_TABLE + " (" + 
                    KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    KEY_NAME + " TEXT NOT NULL, " +
                    KEY_LATITUDE + " DOUBLE, " +
                    KEY_LONGITUDE + " DOUBLE);"
            );
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
            onCreate(db);
        }
    }
}
Unihedron
  • 10,902
  • 13
  • 62
  • 72
  • go with @iDroid answer... as it is going to work for me. Thanks iDroid. –  Sep 22 '11 at 06:45

18 Answers18

195

You can try like this:

 //---deletes a particular title---
public boolean deleteTitle(String name) 
{
    return db.delete(DATABASE_TABLE, KEY_NAME + "=" + name, null) > 0;
}

or

public boolean deleteTitle(String name) 
{
    return db.delete(DATABASE_TABLE, KEY_NAME + "=?", new String[]{name}) > 0;
}
Karthik Kompelli
  • 2,104
  • 1
  • 19
  • 22
Shreyash Mahajan
  • 23,386
  • 35
  • 116
  • 188
  • 70
    Vijay's answer is the correct because this solution allows to do an SQL injection which is a security leak. For instance: use the value of the name argument: `name = "TRUE; ;"` => 'any SQL command' will be executed. Of course it is not a problem if there is no GUI for that feature. – bdevay Mar 15 '14 at 12:45
  • @bdevay My answer is about the background task we done with query. So it is not related to the UI. You just have to give information as dynamically so there is no need of security. If you follow the vijay's answer and some one do reverse engineering then you might got information about table with in the database and field you are compering. which i am doing directly in the query so there is no chance to have it leek. – Shreyash Mahajan Dec 01 '14 at 05:57
  • @iDroid Explorer: of course if there is no user input or other kind of external query maniplation possibility then the security risk is not higher than with the other solution. Continue in the next comment... – bdevay Dec 01 '14 at 10:05
  • 2
    ... But I don't agree with the reverse engineering part of your comment. You have to define somewhere and somehow your query which means that reverse engineering is always a possible security leak (even in case of your solution), especially in Java even if the source is obfuscated. It can only raise the hacking time more. On other hand Google's recommendation is using selection arguments, please check this article: [link](http://developer.android.com/training/basics/data-storage/databases.html#DeleteDbRow) – bdevay Dec 01 '14 at 10:06
  • I mean with the concept of not giving static value to the any method or any variable. That should be maximum of dynamical. So that it is more secure then giving static value. Anyway its up to user that how much secure he/she wants to make their app. – Shreyash Mahajan Dec 01 '14 at 11:16
  • @iDroidExplorer i did come across this and i am loving the answer but i gotta ask how you handle this querty from the activity.Ihave beeen stuck on this from a really long while now.Please help – Steve Kamau Jul 06 '15 at 20:11
  • @SteveKamau I hope you have made databaseHelper class where you are doing all the database related operations. Here you can put this method and use it from any activity by making object of this DatabaseHelper class. – Shreyash Mahajan Jul 07 '15 at 05:19
  • @iDroidExplorer please check out my question here-->http://stackoverflow.com/questions/31161944/how-to-delete-a-single-row-in-android-sqlite?noredirect=1#comment50334196_31161944 – Steve Kamau Jul 07 '15 at 18:06
  • @SteveKamau I have answer you on your question. Have a look at that and let me know – Shreyash Mahajan Jul 08 '15 at 04:49
  • You can try like this: //---deletes a particular title--- public boolean deleteTitle(String name) { return db.delete(DATABASE_TABLE, KEY_NAME + "= '"+ name +"'", null) > 0; } Otherwise you get error where it says there is no such column – Dylan Karimagoko Jan 17 '22 at 09:52
164

Try like that may you get your solution

String table = "beaconTable";
String whereClause = "_id=?";
String[] whereArgs = new String[] { String.valueOf(row) };
db.delete(table, whereClause, whereArgs);
slinden77
  • 3,378
  • 2
  • 37
  • 35
Vijay
  • 2,005
  • 1
  • 14
  • 15
64

it's better to use whereargs too;

db.delete("tablename","id=? and name=?",new String[]{"1","jack"});

this is like useing this command:

delete from tablename where id='1' and name ='jack'

and using delete function in such way is good because it removes sql injections.

Enakhi
  • 1,143
  • 10
  • 16
17

Till i understand your question,you want to put two conditions to select a row to be deleted.for that,you need to do:

public void deleteEntry(long row,String key_name) {

      db.delete(DATABASE_TABLE, KEY_ROWID + "=" + row + " and " + KEY_NAME + "=" + key_name, null);

      /*if you just have key_name to select a row,you can ignore passing rowid(here-row) and use:

      db.delete(DATABASE_TABLE, KEY_NAME + "=" + key_name, null);
      */  

}
Hiral Vadodaria
  • 19,158
  • 5
  • 39
  • 56
15

Try this code

public void deleteRow(String value)
{
SQLiteDatabase db = this.getWritableDatabase();       
db.execSQL("DELETE FROM " + TABLE_NAME+ " WHERE "+COlUMN_NAME+"='"+value+"'");
db.close();
}
Community
  • 1
  • 1
Harman Khera
  • 236
  • 2
  • 9
8

Try this code...

private static final String mname = "'USERNAME'";
public void deleteContact()
{
    db.delete(TABLE_CONTACTS, KEY_NAME + "=" + mname, null);
}
Xavi
  • 20,111
  • 14
  • 72
  • 63
Giridharan
  • 4,402
  • 5
  • 27
  • 30
6

This works perfectly:

public boolean deleteSingleRow(String rowId) 
{
    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

You can also refer to this example.

JDJ
  • 4,298
  • 3
  • 25
  • 44
Karthik
  • 167
  • 1
  • 5
  • associated link is dead now .correct one is http://web.archive.org/web/20110309080938/http://blog.sptechnolab.com/2011/03/02/mysql/android-sqlite-insert-update-delete-and-display-data/ – Navoneel Talukdar Apr 29 '16 at 19:34
3

if you are using SQLiteDatabase then there is a delete method

Definition of Delete

int delete (String table, String whereClause, String[] whereArgs)

Example Implementation

Now we can write a method called delete with argument as name

public void delete(String value) {
    db.delete(DATABASE_TABLE, KEY_NAME + "=?", new String[]{String.valueOf(value)});
}

if you want to delete all records then just pass null to the above method,

public void delete() {
    db.delete(DATABASE_TABLE, null, null);
}

Source Of Information

Jayakrishnan
  • 4,457
  • 29
  • 29
2

Guys this is a generic method you can use for all your tables, Worked perfectly in my case.

public void deleteRowFromTable(String tableName, String columnName, String keyValue) {
    String whereClause = columnName + "=?";
    String[] whereArgs = new String[]{String.valueOf(keyValue)};
    yourDatabase.delete(tableName, whereClause, whereArgs);
}
Naveed Ahmad
  • 6,627
  • 2
  • 58
  • 83
2

Try the below code-

mSQLiteDatabase = getWritableDatabase();//To delete , database should be writable.
int rowDeleted = mSQLiteDatabase.delete(TABLE_NAME,id + " =?",
                    new String[] {String.valueOf(id)});
mSQLiteDatabase.close();//This is very important once database operation is done.
if(rowDeleted != 0){
    //delete success.
} else {
    //delete failed.
}
S.I.
  • 3,250
  • 12
  • 48
  • 77
Durgesh
  • 101
  • 7
2

To delete rows from a table, you need to provide selection criteria that identify the rows to the delete() method. The mechanism works the same as the selection arguments to the query() method. It divides the selection specification into a selection clause(where clause) and selection arguments.

    SQLiteDatabase db  = this.getWritableDatabase();
     // Define 'where' part of query.
    String selection = Contract.COLUMN_COMPANY_ID + " =?  and "
                       + Contract.CLOUMN_TYPE +" =? ";
   // Specify arguments in placeholder order.
    String[] selectionArgs = { cid,mode };
    // Issue SQL statement.
    int deletedRows = db.delete(Contract.TABLE_NAME, 
                       selection, selectionArgs);
    return deletedRows;// no.of rows deleted.

The return value for the delete() method indicates the number of rows that were deleted from the database.

Kaveri
  • 1,060
  • 2
  • 12
  • 21
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Thomas Flinkow Mar 29 '18 at 13:46
1

Guys if above solutions don't work for you then try this one also because it worked for me.

public boolean deleteRow(String name) 
{
    return db.delete(DATABASE_TABLE, KEY_NAME + "='" + name +"' ;", null) > 0;
}
aman003
  • 15
  • 5
1

Works great!

public void deleteNewMelk(String melkCode) {
    getWritableDatabase().delete(your_table, your_column +"=?", new String[]{melkCode});
}
Hadi Note
  • 1,386
  • 17
  • 16
0

Try this one:

public void deleteEntry(long rowId) {
    database.delete(DATABASE_TABLE , KEY_ROWID 
        + " = " + rowId, null);}
0
public boolean deleteRow(long l) {
    String where = "ID" + "=" + l;
    return db.delete(TABLE_COUNTRY, where, null) != 0;
}
babiro
  • 95
  • 2
  • 11
0

You can do something like this, sharing my working code snippet

Make sure query is like this

DELETE FROM tableName WHERE KEY__NAME = 'parameterToMatch'

public void removeSingleFeedback(InputFeedback itemToDelete) {
            //Open the database
            SQLiteDatabase database = this.getWritableDatabase();

            //Execute sql query to remove from database
            //NOTE: When removing by String in SQL, value must be enclosed with ''
            database.execSQL("DELETE FROM " + TABLE_FEEDBACKS + " WHERE "
                    + KEY_CUSTMER_NAME + "= '" + itemToDelete.getStrCustName() + "'" +
                    " AND " + KEY_DESIGNATION + "= '" + itemToDelete.getStrCustDesignation() + "'" +
                    " AND " + KEY_EMAIL + "= '" + itemToDelete.getStrCustEmail() + "'" +
                    " AND " + KEY_CONTACT_NO + "= '" + itemToDelete.getStrCustContactNo() + "'" +
                    " AND " + KEY_MOBILE_NO + "= '" + itemToDelete.getStrCustMobile() + "'" +
                    " AND " + KEY_CLUSTER_NAME + "= '" + itemToDelete.getStrClusterName() + "'" +
                    " AND " + KEY_PRODUCT_NAME + "= '" + itemToDelete.getStrProductName() + "'" +
                    " AND " + KEY_INSTALL_VERSION + "= '" + itemToDelete.getStrInstalledVersion() + "'" +
                    " AND " + KEY_REQUIREMENTS + "= '" + itemToDelete.getStrRequirements() + "'" +
                    " AND " + KEY_CHALLENGES + "= '" + itemToDelete.getStrChallenges() + "'" +
                    " AND " + KEY_EXPANSION + "= '" + itemToDelete.getStrFutureExpansion() + "'" +
                    " AND " + KEY_COMMENTS + "= '" + itemToDelete.getStrComments() + "'"
            );

            //Close the database
            database.close();
        }
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
0

The only way that worked for me was this

fun removeCart(mCart: Cart) {
    val db = dbHelper.writableDatabase
    val deleteLineWithThisValue = mCart.f
    db.delete(cons.tableNames[3], Cart.KEY_f + "  LIKE  '%" + deleteLineWithThisValue + "%' ", null)
}


class Cart {
    var a: String? = null
    var b: String? = null
    var c: String? = null
    var d: String? = null
    var e: Int? = null
    var f: String? = null

companion object {
    // Labels Table Columns names
    const val rowIdKey = "_id"
    const val idKey = "id"
    const val KEY_a = "a"
    const val KEY_b = "b"
    const val KEY_c = "c"
    const val KEY_d = "d"
    const val KEY_e = "e"
    const val KEY_f = "f"
   }
}

object cons {
    val tableNames = arrayOf(
            /*0*/ "shoes",
            /*1*/ "hats",
            /*2*/ "shirt",
            /*3*/ "car"
         )
 }
AllanRibas
  • 678
  • 5
  • 14
0

But the Accepted answer Not worked for me. I think String should be In SQL, strings must be quoted. So, in my case this worked for me against the accepted answer :

 database.delete(TABLE_DAILY_NOTES, WORK_ENTRY_CLUMN_NAME + "='" + workEntry+"'", null);
Noor Hossain
  • 1,620
  • 1
  • 18
  • 25