简体   繁体   中英

How i can onUpgrade me database in Android

Can you help me? I want to upgrade my database in application. I need to create new column by name "alarm". How i can do it in method onUpgrade()? ps in google i dont found needed information. and how to save the information with old database to new database

My code:

public static final String DB_NAME = "database.db";
public static final int DB_VESION = 1;
public static final String ID_COLUMN = "_id";
public static final String NOTE_COLUMN = "note";
public static final String DATE_COLUMN = "date_create";
public static final String STATE_COLUMN = "state";
public static final String DAY_STATE_COLUMN = "day_state";
public static final String ALARM_COLUMN = "alarm";
public final String[] allColumns = {ID_COLUMN, DATE_COLUMN, NOTE_COLUMN, STATE_COLUMN, DAY_STATE_COLUMN};
public static final String TABLE_NAME = "notes";

@Override
public void onCreate(SQLiteDatabase db) {
final String CREATE_DB = "CREATE TABLE " + TABLE_NAME + " (" +
ID_COLUMN + " INTEGER PRIMARY KEY AUTOINCREMENT," +
DATE_COLUMN + " LONG  NOT NULL," +
NOTE_COLUMN + " VARCHAR(140) NOT NULL," +
STATE_COLUMN + " INTEGER NOT NULL," +
DAY_STATE_COLUMN + " LONG" +
");";
db.execSQL(CREATE_DB);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
//how i can do this????
onCreate(db);
}

thanks in advance

Since you have already chosen to drop and recreate the table, just add the new column specification to the CREATE TABLE in your onCreate() .

Increment your DB_VESION so that onUpgrade() gets called.

My guess is that you're extending the SQLiteOpenHelper class, to be able to manage your DB.

If that's the case, the constructor's last param is the DB_VERSION. You should increase that number, so that onUpgrade get's called. But be aware that every time you change your DB_VERSION, the onUpgrade method will be called so i'd advice to use a switch to identify each DB upgrade you need to do. Otherwise, you might find yourself trying to add a column that already exists.

If you're looking for the code to add a column, try something like this:

String createAlarmColum = "ALTER TABLE notes ADD COLUMN alarm INT;";
db.execSQL(createAlarmColum);

Hope it helps :)

方法onUpgrade中的代码可能是这样的?

@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { for (int i = oldVersion; i < newVersion; i++) { switch (i) { case 2: String createAlarmColum = "ALTER TABLE notes ADD COLUMN alarm INT;"; db.execSQL(createAlarmColum); ForgetLogManager.showAppLog(createAlarmColum); break; } } }// onCreate(db);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM