Android技術8:SQLite資料升級

來源:互聯網
上載者:User

標籤:android   style   blog   color   strong   io   資料   cti   

由於應用程式的升級,往往伴隨著資料庫的升級,資料庫升級一般設計表的增加與刪除,表添加刪除欄位,資料的備份等操作。

1.資料庫升級

     我們都通過繼承SQLiteOpenHelper類,實現對資料庫的操作和版本升級等。版本升級有關方法 onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);

當版本號碼大於當前資料庫版本號碼,會調用onUpgrade方法。

2.示範資料庫升級

對於表的增刪相對比較簡單,下面示範添加欄位。

2.1未經處理資料庫sql

private static final String SQL="CREATE TABLE IF NOT EXISTS "+TABLE+"("
+"id integer primary key autoincrement,"
+"name varchar"
+ ")";

為兩個欄位 id ,name;

2.2步驟

修改原表表名-->建立新表-->將原來表資料複製到新表-->刪除原表

2.3代碼

 1 private void upgradeTable(SQLiteDatabase db,String tablename){ 2         //1.修改原表表名    alter table TABLENAME rename to NewTableName; 3         db.beginTransaction(); 4         String newTableName=tablename+"_temp"; 5         String sql="alter table "+ tablename +" rename to "+newTableName; 6         Log.i(TAG,sql); 7         db.execSQL(sql); 8         Log.i(TAG, tablename+"--->"+newTableName); 9         10         //2.建立新表 ,且表名為 tablename11         String newSQL="CREATE TABLE IF NOT EXISTS "+tablename+"("12                 +"id integer primary key autoincrement,"13                 +"name varchar,"14                 +"age integer"15                 + ")";16         17         db.execSQL(newSQL);18         Log.i(TAG, tablename+"建立成功");19         20         //3.複製資料21         String copySQL="insert into "+tablename+"(id,name)"+" select id,name from "+newTableName;22         db.execSQL(copySQL);23         Log.i(TAG, "資料複製成功");24         25         //4.刪除暫存資料表26         String deleteSQL="drop table IF EXISTS "+newTableName;27         db.execSQL(deleteSQL);28         Log.i(TAG, newTableName+"刪除成功");29         30         31         db.setTransactionSuccessful();32         db.endTransaction();33     }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.