user667571
user667571

Reputation: 161

In java, how can I delete a sqlite table?

I am developing android app. I have to develop a xml button in my activity, and construct my sqlite database and tables. How can I just let user press a button to delete a table? Thanks.

Upvotes: 16

Views: 40943

Answers (4)

Samir
Samir

Reputation: 6605

As a Singleton method

 // todo DELETE a special field(s)
public boolean deleteFromTable(int yurtId) {
    SQLiteDatabase database = dbHelper.getReadableDatabase();
    final String whereClause = DBHelper.COLUMN_Y_YURT_ID + " =?";
    final String whereArgs[] = {String.valueOf(yurtId)};
    int affectedRows = database.delete(DBHelper.TABLE_NAME_YEMEKCI, whereClause, whereArgs);
    return affectedRows > 0;
}

  // todo DELETE all table 
public boolean deleteTable() {
    SQLiteDatabase database = dbHelper.getReadableDatabase();
    int affectedRows = database.delete(DBHelper.TABLE_NAME_YEMEKCI, null, null);
    return affectedRows > 0;
}

Upvotes: 0

Nlinscott
Nlinscott

Reputation: 796

There is some ambiguity with your question. Note that there is a difference between DELETING a table and DROPPING a table. Deleting the table simply erases all data from its rows:

database.delete(TABLE_NAME, null, null);

After this, you can still reference the table because it still exists, but creating a new one with the same name may be problematic without using the CREATE TABLE IF NOT EXISTS expression in sql.

Using DROP TABLE completely removes the table and it cannot be referenced again unless it is re-created.

As noted by others, this should work if you want it completely removed from the database:

db.execSQL("DROP TABLE IF EXISTS table_Name");

Upvotes: 18

Cthos
Cthos

Reputation: 985

Hard to answer without more context, but the ultimate sqlite query would be:

db.execSQL("DROP TABLE IF EXISTS table_name");

Where db is a reference to a SqliteDatabase object.

Upvotes: 41

krishna
krishna

Reputation: 4099

SQLiteDatabase sdb;
sdb=openOrCreateDatabase("dbname.db", Context.MODE_WORLD_WRITEABLE, null);
sdb.execSQL("DROP TABLE IF EXISTS tablename");

Upvotes: 0

Related Questions