Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SQLite Database, WHY drop table and recreate on upgrade

In the tutorials I am following and a lot of more places I see this, onUpgrade -> drop table if exists, then recreate table.

What is the purpose of this?

private static class DbHelper extends SQLiteOpenHelper{      public DbHelper(Context context) {         super(context, DATABASE_NAME, null, DATABASE_VERSION);     }      @Override     public void onCreate(SQLiteDatabase db) {         db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +                 KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +                 KEY_NAME + " TEXT NOT NULL, " +                 KEY_HOTNESS + " TEXT NOT NULL);"         );       }      @Override     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {         db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);         onCreate(db);     }        } 
like image 530
Esqarrouth Avatar asked Nov 05 '13 15:11

Esqarrouth


People also ask

What is drop table in SQLite?

The DROP TABLE statement removes a table added with the CREATE TABLE statement. The name specified is the table name. The dropped table is completely removed from the database schema and the disk file. The table can not be recovered. All indices and triggers associated with the table are also deleted.

How do you update a table in SQLite?

Introduction to SQLite UPDATE statement First, specify the table where you want to update after the UPDATE clause. Second, set new value for each column of the table in the SET clause. Third, specify rows to update using a condition in the WHERE clause. The WHERE clause is optional.

Are there restrictions on dropping tables in SQLite?

Normally in SQL you drop foreign keys with the ALTER TABLE statement, but SQLite's ALTER TABLE implementation doesn't allow for dropping constraints. There is a way to deal with this situation though.

What is the main purpose of creating Databasehelper class in SQLite database?

The recommended approach to using SQLite in an Android app is to create a Database Helper class whose only function is to provide for the creation, modification, and deletion of tables in the database.


1 Answers

I agree when you upgrade you should be adding columns or adding tables to your database. Most of the onupgrade samples actually suck because why am I deleting all this data then recreating the table? I found this blog entry I call it the Adams Incremental Update Method. It also handles situations where users may have not upgraded your app with each release.

Here is a good blog on sqlite onupgrade that doesn't do drop table.

like image 56
danny117 Avatar answered Sep 27 '22 19:09

danny117