Well, before you run into big problems, you should know that SQLite is limited by the ALTER TABLE command, it allows add and rename delete only the delete / delete that is performed with the table recreated.
You should always have a new table creation request and use it to update and migrate any existing data. Note: the onUpgrade methods run one for your helper sqlite object, and you need to process all its tables.
So, what is recommended on Upgrade:
- BeginTransaction
- start the creation of the table with
if not exists (we are updating, so the table may not exist yet, it will not be changed and canceled) - enter the existing columns in the list
List<String> columns = DBUtils.GetColumns(db, TableName); - backup table (
ALTER table " + TableName + " RENAME TO 'temp_" + TableName ) - create a new table (latest table creation scheme)
- get the intersection with the new columns, this time the columns taken from the updated table (
columns.retainAll(DBUtils.GetColumns(db, TableName)); ) - restore data (
String cols = StringUtils.join(columns, ","); db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s from temp_%s", TableName, cols, cols, TableName)); ) - delete backup table (
DROP table 'temp_" + TableName ) - setTransactionSuccessful
(This does not handle dropping the table; if you rename a column, you do not get the existing data passed in because the column names do not match).
.
public static List<String> GetColumns(SQLiteDatabase db, String tableName) { List<String> ar = null; Cursor c = null; try { c = db.rawQuery("select * from " + tableName + " limit 1", null); if (c != null) { ar = new ArrayList<String>(Arrays.asList(c.getColumnNames())); } } catch (Exception e) { Log.v(tableName, e.getMessage(), e); e.printStackTrace(); } finally { if (c != null) c.close(); } return ar; } public static String join(List<String> list, String delim) { StringBuilder buf = new StringBuilder(); int num = list.size(); for (int i = 0; i < num; i++) { if (i != 0) buf.append(delim); buf.append((String) list.get(i)); } return buf.toString(); }
Pentium10 Aug 17 '10 at 19:01 2010-08-17 19:01
source share