Sqlite的事务

首先Sqlite 需要写个类继承SqliteOpenHelper
···
public class MySQLHelper extends SQLiteOpenHelper{

public MySQLHelper(Context context){
    super(context, "bankdb", null, 1);
    
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table money(id integer primary key autoincrement,name varchar(20),count folat(11,3)) ");
    db.execSQL("insert into money values(null,'张三',1000)");
    db.execSQL("insert into money values(null,'李四',0)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    
}

}
···
MainActivity中:
···
findViewById(R.id.bt1).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
             MySQLHelper mySQLHelper = new MySQLHelper(MainActivity.this);
               SQLiteDatabase rd = mySQLHelper.getReadableDatabase();
              //开启事务
               rd.beginTransaction();
               
               rd.execSQL("update money set count=count-300 where name='张三'");
               
               rd.execSQL("update money set count=count+300 where name='李四'");
              //提交事务
               rd.setTransactionSuccessful();
            //关闭确认
               rd.endTransaction();
            rd.close();
            mySQLHelper.close();
            Toast.makeText(MainActivity.this, "转账成功", Toast.LENGTH_SHORT).show();
            
        }
    });
  
}

}
···

你可能感兴趣的:(Sqlite的事务)