/** * 银行转账操作 */ public void transation(){ db.beginTransaction(); try { //name为微明的用户向小红转账 ContentValues contentValues=new ContentValues(); contentValues.put("money", 1000); db.update("person", contentValues, "name=?", new String[]{"微明"}); ContentValues contentValues2=new ContentValues(); contentValues2.put("money", 1100); db.update("person", contentValues2, "name=?", new String[]{"小红"}); //全部语句运行完毕,若没有异常,则会运行这句设置事务成功的标记 db.setTransactionSuccessful(); } finally { //会检查事务的标识,若没有调用setTransactionSuccessful()方法设置标志,则回滚事务。否则提交事务。 db.endTransaction(); } } } MyOpenHelper.java **SQLiteOpenHelper: * A helper class to manage database creation and version management. * 所以,SQLiteOpenHelper是对库本身的操作。若要对库中数据操作,须要使用库对象的方法。 */ import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class MyOpenHelper extends SQLiteOpenHelper { //name:数据库文件的名字 //factory:游标工厂 //version:版本号,必须大于等于1 public MyOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub } //数据库创建时调用 @Override public void onCreate(SQLiteDatabase db) { //创建一个person表 db.execSQL("create table person(_id integer primary key autoincrement, name char(10), phone char(20))"); System.out.println("oncreate调用了"); } //数据库升级时调用 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub System.out.println("onupgrade调用了"); db.execSQL("alter table person add money char(20)"); } } |