android 之sqlite事务

1.什么是事务?

事务产生的原因是由于事务的原子性导致的,事务的成功与否与逻辑与有点相似,都成功则事务为真反之亦然。

2。例子:

事务的运用非常广泛,比如在银行给别人汇款的时候,从A账户汇款到B账户,其中数据库层次的操作是

将A的余额减去汇款的余额然后B帐号再加上汇款的余额,如果在这一过程中出现了其他意外情况,比如断网、电 etc其他无法预知的错误时候,

A的余额和B的余额又该成为多少呢?这个时候就引入了事务。

3.sqlite demo:


package com.example.root.p120;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyHelper helper = new MyHelper(this);
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("f1",100);
        values.put("f2",200);

        db.insert("test",null,values);
        db.beginTransaction();//开始事务
        try{
            db.execSQL("update test set f1=101 where id=1");
            db.execSQL("update test set f2=103 where id=1");
            db.setTransactionSuccessful();//设置事务处理成功
        }catch(Exception e){
            Log.i("事务处理失败!",e.toString());
        }finally{
            db.endTransaction(); //关闭事务
            db.close();
        }



    }
}

class MyHelper extends SQLiteOpenHelper {
    public MyHelper(Context context){
        super(context,"test.db",null,1);
    }

    public void onCreate(SQLiteDatabase db){
        db.execSQL("create table test(id integer primary key autoincrement," +
                "f1 integer not null," +
                "f2 integer not null)");
    }

    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
        db.execSQL("alter table test add column f3 integer");
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值