In java, how can I delete a sqlite table?

2020-08-10 07:06发布

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.

4条回答
我命由我不由天
2楼-- · 2020-08-10 07:31

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;
}
查看更多
混吃等死
3楼-- · 2020-08-10 07:33
SQLiteDatabase sdb;
sdb=openOrCreateDatabase("dbname.db", Context.MODE_WORLD_WRITEABLE, null);
sdb.execSQL("DROP TABLE IF EXISTS tablename");
查看更多
做自己的国王
4楼-- · 2020-08-10 07:44

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.

查看更多
劫难
5楼-- · 2020-08-10 07:48

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");
查看更多
登录 后发表回答