Upgrading database version automatically

2019-06-14 14:04发布

问题:

Hi i am creating an app which stores the password of the user entering. and whenever he needs to change his password then the data has to be changed. The problem i am facing is while i am calling the DBHelper class (i created to do all my database works) its not deleting the table if it is available.

It will be more helpful if someone tells me how to delete the entries in the table while calling the DBHelper class.

I realized that the OnCreate and OnUpgrade functions are not executing except the first time while creating the database.

also changing database version automatically also helps i guess but i don't know how to do?? here is my code from DBhelper class

public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
          db.execSQL("DROP TABLE IF EXISTS '" + DATABASE_TABLE+"'");
          db.execSQL("CREATE TABLE " + DATABASE_TABLE +" (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
                KEY_ID +" INTEGER, "+
                KEY_X +" INTEGER,  "+
                KEY_Y +" INTEGER);"
                );  

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS '" + DATABASE_TABLE+"'");
        onCreate(db);
    }

public long createEntry(int name, int sx, int sy) {
        // TODO Auto-generated method stub
        ContentValues cv=new ContentValues();
        cv.put(KEY_ID, name);
        cv.put(KEY_X, sx);
        cv.put(KEY_Y, sy);
        return ourDatabase.insert(DATABASE_TABLE, null, cv);
    }

回答1:

Changing a row in the database should not affect the schema version. This should be executed as proper queries to manipulate the database entries.

You might find use of this method:

public void clearDatabase(Context context) {
   DatabaseHelper helper = new DBHelper(context);
   SQLiteDatabase database = helper.getWritableDatabase();
   database.delete(DATABASE_TABLE, null, null); //erases everything in the table.
   database.close();
}


回答2:

First of all here is how you can change the database version programmatically and hence force the SQLiteOpenHelper to call onUpgrade() on the next call to open the database:

db.execSQL("PRAGMA user_version = " + NEW_VERSION);

Second, I don't recommend using this technique. I only wrote this answer cause you asked about how to do it this way. It's your choice. For me I'll do it the way @Boris Strandjev recommends in his answer.