Well, before you encounter major problems, you should know that SQLite limited ALTER TABLE command, it allows add, and renameremove only the removal / deletion is performed with the re-creation of the table.
. : onUpgrade sqlite, .
, Upgrade:
- BeginTransaction
if not exists ( , , )List<String> columns = DBUtils.GetColumns(db, TableName);- (
ALTER table " + TableName + " RENAME TO 'temp_" + TableName) - ( )
- , , (
columns.retainAll(DBUtils.GetColumns(db, TableName));) - (
String cols = StringUtils.join(columns, ",");
db.execSQL(String.format(
"INSERT INTO %s (%s) SELECT %s from temp_%s",
TableName, cols, cols, TableName));
) - (
DROP table 'temp_" + TableName) - setTransactionSuccessful
( , , , , ).
.
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();
}