Android學習筆記_資料庫(SQLite)(二)

來源:互聯網
上載者:User

標籤:

一、修改資料庫的表結構(更新資料庫版本)。

  1、在PersonSQliteOpenHelper類中,PersonSQliteOpenHelper的構造方法中需要傳入4個參數,最後一個便是資料庫版本。當版本數值變化(只能是增加)時就會調用PersonSQliteOpenHelper類中的onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)方法。

  2、在onUpgrade方法中採用執行SQL語句來更改資料庫的表結構。採用SQLiteDatabase對象的execSQL(sql)方法修改資料庫的表結構,參數sql是需要執行的SQL語句。

  3、表中增加一列的SQL語句是:ALTER TABLE person ADD account varchar(20).

表結構增加一列的代碼如下:

1 public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {2         db.execSQL("alter table person add account varchar(20)");3     }
View Code

二、資料庫的事務  

  1、為何需要事務?

    保證多個操作同時成功或者同時失敗時採用事務。比如銀行轉賬:A轉帳給B,需要保證A賬戶中金額減少,同時還需要保證B賬戶中金額增加。一下介紹以類比轉賬為例。因此需要修改資料庫的表結構

  2、建立事務。

    ①.new出來一個PersonSQliteOpenHelper對象helper;

    ②.通過PersonSQliteOpenHelper對象的getWritableDatabase()方法獲得一個可寫的SQLiteDatabase(資料庫)對象db;

    ③.通過SQLiteDatabase(資料庫)對象的beginTransaction()方法開啟一個事務(事務的具體寫法在該方法的說明文檔中已經有執行個體了:採用一個try...finally的邏輯編寫事務);

    ④.在try中編寫需要執行的邏輯,並在try代碼塊的最後執行SQLiteDatabase(資料庫)對象的setTransactionSuccessful()的方法,它是標記資料庫事務執行成功,如果沒有這個代碼則預設是執行失敗的,資料會復原。

    ⑤.在finally代碼塊中執行SQLiteDatabase(資料庫)對象的endTransaction()方法,並close資料庫物件。另外也可以在try代碼塊後面增加一個catch代碼塊,以捕獲各類異常。

資料庫事務代碼如下:

 1 public void testTransecation() throws Exception { 2         PersonSQliteOpenHelper helper = new PersonSQliteOpenHelper(getContext()); 3         SQLiteDatabase db = helper.getWritableDatabase(); 4         db.beginTransaction(); 5         try { 6             db.execSQL("update person set account = account - 1000 where name = ?", 7                     new Object[] { "zhangsan" }); 8              9             db.execSQL(    "update person set account = account + 1000 where name = ?",10                     new Object[] { "wangwu" });11             db.setTransactionSuccessful();12         }catch(Exception e) {13             14         }15         finally {16             db.endTransaction();17             db.close();18         }        19     }
View Code

 

Android學習筆記_資料庫(SQLite)(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.