Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

android - Delete all tables from sqlite database

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 database and I tried to delete the tables using the retrieved table names one by one. It didn't work as well.

Please suggest me a method to delete all tables from the database.

This is the code that I used:

public void deleteall(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
    do
    {
        db.delete(c.getString(0),null,null);
    }while (c.moveToNext());
}

function deleteall() is called on button click whos code is given as below:

public void ButtonClick(View view)
{
    String Button_text;
    Button_text = ((Button) view).getText().toString();

    if(Button_text.equals("Delete Database"))
    {
        DatabaseHelper a = new DatabaseHelper(this);
        a.deleteall();
        Toast.makeText(getApplicationContext(), "Database Deleted Succesfully!", Toast.LENGTH_SHORT).show();
    }}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...