How to use transactions SQlite? Maybe I was looking bad, but I did not find how to do it right. I execute everything in AsyncTask. Here is the code:

DbOpenHelper dbOpenHelper = new DbOpenHelper(MainActivity.this); SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); ContentValues qcv = new ContentValues(); db.beginTransaction(); try { for (int k = 0; k < 10; k++) { qcv.put(DbOpenHelper.ID, 200 + k); qcv.put(DbOpenHelper.KEY1, "value1"); qcv.put(DbOpenHelper.KEY2, "value2"); db.insert(DbOpenHelper.TABLE2_NAME, null, qcv); db.setTransactionSuccessful(); } } finally { db.endTransaction(); } 
  • db.setTransactionSuccessful (); in my opinion, it is necessary to take out of the cycle, and transactions are necessary in order to be able to roll back the changes in the form of a sequence of actions. For example, for a program to work, you need to make a single table, then an insert and update to other several threads simultaneously with the same data, one will not work - you can roll back. - Raskilas
  • The fact is that the use of transactions, as far as I know, allows you to increase performance at times, because It does not open / close the database when writing each item. - andgo75
  • one
    @ andgo75 is a misconception. It all depends on the level of transaction isolation. The higher the level of insulation, the lower the speed. The default level is usually the READ_UNCOMMITTED level - the highest speed is reached. So sir you are mistaken - Barmaley


2 answers 2

It is necessary so:

 try { db.beginTransaction(); ///// работа с бд: select, update, insert... for (int k = 0; k < 10; k++) { // если внутри цикла нужно зафиксировать транзакцию, // (например, после обработки 100 insert'ов) // то пишем условие и: // db.setTransactionSuccessful(); // db.endTransaction(); // db.beginTransaction(); qcv.put(DbOpenHelper.ID, 200 + k); qcv.put(DbOpenHelper.KEY1, "value1"); qcv.put(DbOpenHelper.KEY2, "value2"); db.insert(DbOpenHelper.TABLE2_NAME, null, qcv); } db.setTransactionSuccessful(); } catch(...) { ... } finally { db.endTransaction(); } db.close(); 

    good practice. open the database in Application and close there.