开发者

Using multiple methods in a transaction

I'm making an Android app, which gets its information from XML files. I'm filling the information in a database, for easier acces during the program's runtime, thanks to the power of queries.

However it came to my attention, that using Transactions greatly improves speed, so naturally, I want to use that.

My problem is the following tho; In the idea of abstraction, after parsing all the information of one subject, the information gets send to the correct entity (class), and inside that entity there is a method that will add it in the database. After that, it returns to the parser which continues to read the next subject, which in it's turn will be send to right (and probably different) class again.

This is implemented with a switch statement, with every case pointing to a different class constructor.

If I want to use the speed of transactions, I would need to start a transaction already before the parsing, run through the parsing and query building (as far as I understand, all queries build within the transaction, are collected and in the end all executed as a bunch) and then end the transaction, once the whole file is parsed.

To make this a bit clearer, or faster to read; The code idea would be;

    Cl开发者_Go百科ass parser(){
  database.beginTransaction();
    try{  
         // start parsing in a whole different class, which also points to SQL queries (in different classes again) in the entitys with a switch
       }catch(Exception e){
    database.endTransaction();
       }
        database.endTransaction();
}

I hope i formulated my question clearly enough.

Kind regards,


Yes, you've got the general idea. However, you need to be careful to mark the transaction as successful when you finish parsing, and also to ensure the transaction is always closed even in the event of an exception.

Example from the docs:

db.beginTransaction();
try {
    // do all the parsing in here
    ...
    db.setTransactionSuccessful();
} finally {
    db.endTransaction();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜