Android中SQLite事務的操作

來源:互聯網
上載者:User

標籤:android   sqlite   事務   安卓   資料庫   

1.建立一個資料庫協助類。

package com.wzw.sqllitedemo.db;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;/** *  * 資料庫協助類,用於建立管理資料庫 * @author Administrator * */public final class PersonSQLiteOpenHelper extends SQLiteOpenHelper {private String tag="PersonSQLiteOpenHelper";/** * 資料庫的建構函式 * @param context * @param name資料庫名稱 * @param factory遊標工廠 * @param version版本 */public PersonSQLiteOpenHelper(Context context) {super(context, "my.db", null, 2);}/** * 資料庫第一次建立時調用此方法 * 用於初始化表 */@Overridepublic void onCreate(SQLiteDatabase db) {//SQLiteDatabase對象已經串連資料庫,直接進行性資料庫操作String sql="create table person(_id integer primary key,name varchar(15),age integer);";db.execSQL(sql);//建立person表}/** * 資料庫的版本號碼更新時調用 * 用於更新資料庫的內容(刪除表,更新表,刪除表) */@Overridepublic void onUpgrade(SQLiteDatabase db, int  oldVersion, int newVersion) {if(oldVersion==1&&newVersion==2){//資料庫更新,增加balance餘額列,事務的處理Log.i(tag, "資料庫更新了");db.execSQL("alter table person add balance integer");}}}

資料庫表person中分別有id,name,age,banlance列


2.建立一個junit test類來測試

package com.wzw.sqllitedemo.test;import java.util.List;import com.wzw.sqllitedemo.dao.PersonDao;import com.wzw.sqllitedemo.db.PersonSQLiteOpenHelper;import com.wzw.sqllitedemo.entities.Person;import android.database.sqlite.SQLiteDatabase;import android.test.AndroidTestCase;import android.util.Log;public class TestCase extends AndroidTestCase {private String tag="TestCase";public void test(){//資料庫什麼時候建立PersonSQLiteOpenHelper openHelp=new PersonSQLiteOpenHelper(getContext());//第一次串連資料庫的時建立資料庫,oncreate調用openHelp.getWritableDatabase();}public void testTransaction(){PersonSQLiteOpenHelper openHelper=new PersonSQLiteOpenHelper(getContext()); //擷取資料庫協助類SQLiteDatabase db=openHelper.getWritableDatabase();//獲得可寫資料庫if(db.isOpen()){//如果資料庫可讀,進行操作//1.從張山扣1000try{db.beginTransaction();db.execSQL("update person set balance=balance-1000 where name='zhangsan';");//ATM出異常//int tes=1/0;//2.向李四加1000元db.execSQL("update person set balance=balance+1000 where name='lisi';");db.setTransactionSuccessful();//標記事務成功!}finally{db.endTransaction();db.close();}}}}

事務中必須調用setTransactionSuccessful()來標識事務成功。




初學安卓,記錄點點滴滴。

聯繫我們

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