SQLITE Busy Handling

Discussion in 'iOS Programming' started by tdog09, Feb 4, 2011.

  1. macrumors member

    Joined:
    Jul 13, 2008
    #1
    Hey guys, need a little bit of help.

    I'm using sqlite3 and updating a few tables throughout the use of my app.

    My typical update code goes like this (after opening the database):

    Code:
    
    char *errorMsg;
    NSString *update = [[NSString alloc] initWithFormat: @"Update PRSN_POINTS SET POINTS = 3"];
    
    if (sqlite3_exec (database, [update UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK){
    
      NSAssert1(0, @"Error updating table:, %s", errorMsg);
    )
    
    
    This works fine, but since my app is Multi Threaded :)eek:) every now and then I find that two threads will be trying to access and update the same table at the same time. The error code I get back is SQLITE_BUSY as it cannot contain a DB LOCK.

    My question is what is the correct way to handle this? I would think that I should have it sleep for a just a little, then retry. I'm not quite sure how to accomplish this, so any suggestions and code inserts would be great. Also I haven't looked a whole lot into Core Data, but would it have any advantages in this area? My code's quite infused with SQLITE, and I would rather not have to scrap it.

    Thanks!
     
  2. macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    I believe that FMDB manages this. If you don't want to use FMDB directly then you can look at its code.
     
  3. thread starter macrumors member

    Joined:
    Jul 13, 2008
    #3
    Thanks, are there more resources on how to use FMDB?
     
  4. macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #4
    Unfortunately documentation is a weak point for FMDB. On the good side it's not very much code and you get all of the code to read yourself.

    There is one example file that shows the basics.

    To use an FMDB database from a thread all you do is create another database object on each thread. It should "just work" in that case. I've had no problems using it from multiple threads concurrently.
     
  5. thread starter macrumors member

    Joined:
    Jul 13, 2008
    #5
    Thanks for help! I started looking at it and using it in my code. Question, does an AutoRelease Pool need to be created each time I create a new database object? Thanks!
     
  6. macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #6
    I don't think so. Why do you ask?

    If you're asking about a db on a thread then the normal memory management for threads applies. It's certainly possible that iterating over a result set will generate a lot of autoreleased objects and you might use a local autorelease pool for that. If that's what you're asking.
     

Share This Page