Delete all tables from sqlite database

后端 未结 4 1715
感情败类
感情败类 2020-12-17 10:06

I have done a lot of research and was unable to find a suitable method to delete all the tables in an SQLite database. Finally, I did a code to get all table names from the

相关标签:
4条回答
  • 2020-12-17 10:49

    Tim Biegeleisen's answer almost worked for me, but 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 shouldn't 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<String> 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();
        }
    }
    
    0 讨论(0)
  • 2020-12-17 10:52

    For me, the working solution is:

        Cursor c = db.rawQuery(
                "SELECT name FROM sqlite_master WHERE type IS 'table'" +
                        " AND name NOT IN ('sqlite_master', 'sqlite_sequence')",
                null
        );
        if(c.moveToFirst()){
            do{
                db.execSQL("DROP TABLE " + c.getString(c.getColumnIndex("name")));
            }while(c.moveToNext());
        }
    
    0 讨论(0)
  • 2020-12-17 10:56

    Use DROP TABLE:

    // query to obtain the names of all tables in your database
    Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
    List<String> tables = new ArrayList<>();
    
    // iterate over the result set, adding every table name to a list
    while (c.moveToNext()) {
        tables.add(c.getString(0));
    }
    
    // call DROP TABLE on every table name
    for (String table : tables) {
        String dropQuery = "DROP TABLE IF EXISTS " + table;
        db.execSQL(dropQuery);
    }
    
    0 讨论(0)
  • 2020-12-17 11:02

    delete database instead of deleting tables and then create new with same name if you need. use following code

    context.deleteDatabase(DATABASE_NAME); 
              or
    context.deleteDatabase(path);
    
    0 讨论(0)
提交回复
热议问题