vje1998
vje1998

Reputation: 691

Sqlite DB Locked

-(void)insertQuery:(NSString *)query{
    sqlite3_stmt *selectstmt;
    // Create a sqlite object.
    sqlite3 *database;
    // Set the database file path.
    NSString *databasePath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];

    if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
        //*************** insert value in database******************************\\

        const char *sql = [query UTF8String];
        sqlite3_prepare_v2(database,sql, -1, &selectstmt, NULL);
        if(sqlite3_step(selectstmt)==SQLITE_DONE)
        {
            NSLog(@"insert successfully");
        }
        else
        {
            NSLog(@"insert not successfully");
            NSLog(@"DB Error: %s", sqlite3_errmsg(database));
        }
        sqlite3_finalize(selectstmt);
    }
    sqlite3_close(database);
}

Using above code trying to fire insert query but sometime it works and most of the time i get DB locked error.

For helping hands Thanks in advance.

Upvotes: 0

Views: 232

Answers (3)

Prakash
Prakash

Reputation: 157

Use this link and manage your Database with this using FMDB. I also faced this problem 5 months back and used this and my problem resolved 100%.

Upvotes: 2

Adnan Yaqoob
Adnan Yaqoob

Reputation: 66

Database lock usually happens when you are writing something to database or you have left some other connection open. Check you other code for lose connections.

Try to check for SQLITE_OK for sqlite3_prepare_v2 because database may be busy and may return SQLITE_BUSY for step statement. Further explained here. Try following code:

if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
    //*************** insert value in database******************************\\

    const char *sql = [query UTF8String];
    if(sqlite3_prepare_v2(database,sql, -1, &selectstmt, NULL)==SQLITE_OK)
    {
      if(sqlite3_step(selectstmt)==SQLITE_DONE)
      {
          NSLog(@"insert successfully");
      }
      else
      {
          NSLog(@"insert not successfully");
          NSLog(@"DB Error: %s", sqlite3_errmsg(database));
      }
      sqlite3_finalize(selectstmt);
    }
    sqlite3_close(database);
}

Upvotes: 0

El Tomato
El Tomato

Reputation: 6707

You are not closing the connection properly.

if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
    //*************** insert value in database******************************\\

    const char *sql = [query UTF8String];
    sqlite3_prepare_v2(database,sql, -1, &selectstmt, NULL);
    if(sqlite3_step(selectstmt)==SQLITE_DONE)
    {
        NSLog(@"insert successfully");
    }
    else
    {
        NSLog(@"insert not successfully");
        NSLog(@"DB Error: %s", sqlite3_errmsg(database));
    }
    sqlite3_finalize(selectstmt);
    sqlite3_close(database);
}

Upvotes: 0

Related Questions