Drop all tables command

后端 未结 10 577
滥情空心
滥情空心 2020-11-28 23:52

What is the command to drop all tables in SQLite?

Similarly I\'d like to drop all indexes.

10条回答
  •  醉梦人生
    2020-11-28 23:55

    I had this issue in Android and I wrote a method similar to it-west.

    Because I used AUTOINCREMENT primary keys in my tables, there was a table called sqlite_sequence. SQLite would crash when the routine tried to drop that table. I couldn't catch the exception either. Looking at https://www.sqlite.org/fileformat.html#internal_schema_objects, I learned that there could be several of these internal schema tables that I didn't want to drop. The documentation says that any of these tables have names beginning with sqlite_ so I wrote this method

    private void dropAllUserTables(SQLiteDatabase db) {
        Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
        //noinspection TryFinallyCanBeTryWithResources not available with API < 19
        try {
            List tables = new ArrayList<>(cursor.getCount());
    
            while (cursor.moveToNext()) {
                tables.add(cursor.getString(0));
            }
    
            for (String table : tables) {
                if (table.startsWith("sqlite_")) {
                    continue;
                }
                db.execSQL("DROP TABLE IF EXISTS " + table);
                Log.v(LOG_TAG, "Dropped table " + table);
            }
        } finally {
            cursor.close();
        }
    }
    

提交回复
热议问题