zgz345

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

假设要更新TableC表,建议的做法是:       

1) 将TableC重命名为TableC_temp

       SQL语句可以这样写:ALERT TABLE TableC RENAME TO TableC_temp;

2) 创建新的TableC表

3) 将数据从TableC_temp中插入到TableC表中

       SQL语句可以这样写:INSERT INTO TableC (Col1, Col2, Col3) SELECT (Col1, Col2, Col3) FROM TableC_temp;                

                   
经过这三步,TableC就完成了更新,同时,也保留了原来表中的数据。 

注意:

在onUpgrade()方法中,删除表时,注意使用事务处理,使得修改能立即反应到数据库文件中。 

protected void upgradeTables(SQLiteDatabase db, String tableName, String columns)  
{  
    try  
    {  
        db.beginTransaction();  
  
        // 1, Rename table.  
        String tempTableName = tableName + "_temp";  
        String sql = "ALTER TABLE " + tableName +" RENAME TO " + tempTableName;  
        execSQL(db, sql, null);  
  
        // 2, Create table.  
        onCreateTable(db);  
  
        // 3, Load data  
        sql =   "INSERT INTO " + tableName +  
                " (" + columns + ") " +  
                " SELECT " + columns + " FROM " + tempTableName;  
  
        execSQL(db, sql, null);  
  
        // 4, Drop the temporary table.  
        execSQL(db, "DROP TABLE IF EXISTS " + tempTableName, null);  
  
        db.setTransactionSuccessful();  
    }  
    catch (SQLException e)  
    {  
        e.printStackTrace();  
    }  
    catch (Exception e)  
    {  
        e.printStackTrace();  
    }  
    finally  
    {  
        db.endTransaction();  
    }  
}  

 

posted on 2014-12-16 13:38  zonyZhang  阅读(1516)  评论(0编辑  收藏  举报