title: sqlite error database is locked
body: <p>I am have a sqlite database in the iPhone application I am writing. I get an error with following code that I am running in a background thread. In the background thread, I call this method:</p>
  
  <pre><code> - (BOOL) songIsInDatabase:(NSString *)songTitle
  {
  NSString *docsDir;
  NSArray *dirPaths;
  
  dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  docsDir = [dirPaths objectAtIndex:0];
  
  
  //Build the path to the database file
  NSString *databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"Database.db"]];
  
  const char *dbpath = [databasePath UTF8String];
  
  sqlite3_stmt *statement;
  
  if(sqlite3_open(dbpath, &amp;DB) == SQLITE_OK){
  
      NSString *insertSQL = [NSString stringWithFormat:@"select * from Bpm_Table where song_title = '%@'", songTitle];
  
      const char *insert_stmt = [insertSQL UTF8String];
      if(sqlite3_prepare_v2(DB, insert_stmt, -1, &amp;statement, NULL) == SQLITE_OK)
      {
          while (sqlite3_step(statement) == SQLITE_ROW)
          {
              return YES;
              break;
          }
      }else{
          NSLog(@"the error is %s", sqlite3_errmsg(DB));
      }
      sqlite3_finalize(statement); 
  }
  
  [databasePath release];
  return NO;
  }
  </code></pre>
  
  <p>Then I call this method:</p>
  
  <pre><code>- (void) addSongToDatabase: (NSString *) songTitle andBPM: (int)bpm andGenre: (NSString *) genre
  {
  NSString *docsDir;
  NSArray *dirPaths;
  
  dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  docsDir = [dirPaths objectAtIndex:0];
  
  
  //Build the path to the database file
  NSString *databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"Database.db"]];
  
  const char *dbpath = [databasePath UTF8String];
  
  sqlite3_stmt *statement;
  
  if(sqlite3_open(dbpath, &amp;DB) == SQLITE_OK){
  
      NSString *insertSQL = [NSString stringWithFormat:@"insert or replace into Bpm_Table (song_title, bpm, genre) values (\"%@\", \"%d\", \"%@\")", songTitle, bpm, genre];
  
      const char *insert_stmt = [insertSQL UTF8String];
      if(sqlite3_prepare(DB, insert_stmt, -1, &amp;statement, NULL) == SQLITE_OK){
          if(sqlite3_step(statement) == SQLITE_DONE)
          {
  
          } else {
              NSLog(@"error: %s", sqlite3_errmsg(DB));
          }
      }sqlite3_finalize(statement);
  }
  
  [databasePath release];
  }
  </code></pre>
  
  <p>If I run both these methods, one right after the other,  I get an error that says <strong>database is locked</strong>. I added the <code>sqlite3_finalize</code> statements after poking around google in hopes that would fix the issue. If I comment out either of the methods, I don't get this error. </p>
  
  <p>Does anyone know what's wrong?</p>