venerdì 16 novembre 2012

Android e un "alter table" su database SQLite

Ci sono diversi modi di eseguire un "alter table" su SQLite di Android nel caso manchi o si voglia aggiornare un campo su di una tabella.
Eccone un esempio dove prima viene effettuato un test di esistenza del campo e in caso negativo si procede alla sua creazione:

SQLiteDatabase db;
OpenHelper openHelper = new OpenHelper(this.context); 
this.db = openHelper.getWritableDatabase(); 

try{
 /* check if field exists */
 String sql ="select sql from sqlite_master where " + 
  "tbl_name = 'tbl_example' and sql like '%field_price INTEGER%'";    
 
 long lngResult = DatabaseUtils.longForQuery(arg0,sql, null);
 
}catch(SQLException e){
 upgradeToVersion(this.db);
}
 
private void upgradeToVersion(SQLiteDatabase db) {
 try{
  /* add an integer field */
  db.execSQL("ALTER TABLE tbl_example " ADD " + 
   "field_price INTEGER");
 }catch(SQLException e){}
}