码迷,mamicode.com
首页 > 数据库 > 详细

sqlite(2、事务)

时间:2015-01-27 10:54:31      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

sqlite默认每条执行语句都是一个事务,因此增加事务除了会进行原子性的保护外,也可提升性能,减少磁盘操作。使用SQLite的beginTransaction()方法可以开启一个事务,执行到endTransaction()方法是会检查事务的标志是否为成功,如果成功则提交事务,否则回滚事务。

当应用程序需要提交事务,必须在程序到endTransaction()方法之前使用setTransactionSuccessfull()方法设置事务的标志为成功。若果如果不调用setTransactionSuccessful()不设置事务标志的话,默认回滚。

程序实例如下:

SQLiteDatabase db = openOrCreateDatabase("demo.db", this.MODE_PRIVATE, null);
        db.execSQL("CREATE TABLE IF NOT EXISTS users (_id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR, password VARCHAR)");
        //开启事务  
        db.beginTransaction();  
        try  
        {  
             db.execSQL("INSERT INTO users VALUES (NULL,‘fredric1‘,‘fredricpassword1‘)");  
             db.execSQL("INSERT INTO users VALUES (NULL,‘fredric2‘,‘fredricpassword2‘)"); 
             db.execSQL("INSERT INTO users VALUES (NULL,‘fredric3‘,‘fredricpassword3‘)");
             db.execSQL("INSERT INTO users VALUES (NULL,‘fredric4‘,‘fredricpassword4‘)");
            //设置事务标志为成功,当结束事务时就会提交事务  
            db.setTransactionSuccessful();  
        }  
        finally  
        {  
            //结束事务  
            db.endTransaction(); 
            Cursor cursor = db.rawQuery("SELECT * FROM users", null);
             
             while (cursor.moveToNext()) { 
                 
                 Log.i(TAG_ACTIVITY, cursor.getString(cursor.getColumnIndex("username")));
                 Log.i(TAG_ACTIVITY, cursor.getString(cursor.getColumnIndex("password")));             
             }
             
             cursor.close();
        }
    }

 

sqlite(2、事务)

标签:

原文地址:http://www.cnblogs.com/Fredric-2013/p/4251891.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!