房间数据库事务回滚

时间:2018-01-05 12:02:59

标签: android sqlite android-room

使用会议室数据库,我正在执行来自不同Private Sub Worksheet_Change(ByVal Target As Range) Dim cell As Range For Each cell In Target Dim r As Integer r = cell.Row 'If Application.Intersect(cell, Range("f5:f5000")) Is Nothing Then ' 1. This is not really needed. If the next condition is true, this one will never be. If Not (Application.Intersect(cell, Range("A5:C5000")) Is Nothing) Then 'Sum = Application.Sum(Application.Intersect(cell, Range("f5:f5000"))) ' 2. This Intersection will always be empty... Sum = Application.Sum(Range("F5:F7")) ' 2... Using here a hardcoded Range. You should adapt this. Dim ctmp As Range ' 3. Use of auxiliary variables is always encouraged 'Set ctmp = Application.Intersect(cell, Range("f5:f5000")) ' 4. Again, this Intersection will always be empty. Set ctmp = Range("F" & CStr(r)) If Sum > 100 Then 'ctmp.Interior.Color = RGB(255, 0, 0) ' 5. Alternative definition of color ctmp.Interior.Color = vbRed Else 'ctmp.Interior.Color = RGB(255, 255, 255) ctmp.Interior.Color = vbWhite End If End If 'End If ' 1... Next 'End If ' 6. Spurious EndIf End Sub 的多个DELETE + INSERT个查询。

我正在使用交易:

DAO's

如果有任何失败,有没有办法myDb.runInTransaction(new Runnable() { @Override public void run() { } });

稍后编辑: 使用这种模式似乎有效:

ROLLBACK

2 个答案:

答案 0 :(得分:1)

如果发生异常,事务将不会设置为成功,这意味着它将在事务结束时回滚。这是code for runInTransaction()

public void runInTransaction(Runnable body) {
    beginTransaction();
    try {
        body.run();
        setTransactionSuccessful();
    } finally {
        endTransaction();
    }
}

因此,您可以创建以下内容:

try {
    myDb.runInTransaction(new Runnable() {
        @Override
        public void run() {
            // DELETE
            if (failed) {
                throw new Exception("failed"); // ROLLBACK
            }
            // INSERT
        }
    });
} catch (Exception ex) {
    // Error handling
}

同步调用Runnable代码。

而且,如果代码使用lambdas而不是Runnable匿名类,它将看起来更干净。 :)

答案 1 :(得分:0)

希望我的回答对您有所帮助,因为我对您要使用的方法一无所知。

来自Android开发者文档。

 @Dao
public abstract class ProductDao{
    @Insert
     public abstract void insert(Product product);
     @Delete
     public abstract void delete(Product product);
     @Transaction
     public void insertAndDeleteInTransaction(Product newProduct, Product oldProduct) {
         // Anything inside this method runs in a single transaction.
         insert(newProduct);
         delete(oldProduct);
     } 
  }

您必须在方法中使用@Transaction批注,以指示在其中进行的所有更改都将被包装在事务中,因此,如果发生异常,则所有更改都将回滚。 (对不起,我的英语,我还在学习)