AppsDev
AppsDev

Reputation: 12499

Not inserting rows in sqlite database in iOS

I have a method intended to insert in my sqlite database from a custom object:

- (void)insertCustomEntity:(CustomEntity *)customEntity
{
   NSString *filePath = [FileMngr copyDatabaseToDocuments];

   sqlite3 *database;

   if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
       const char *sqlStatement = "INSERT OR REPLACE INTO Entities (id, type, timestamp, result) VALUES (?, ?, ?, ?)";
    sqlite3_stmt *compiledStatement;

        NSLog(@"Could not prepare statement: %s\n", sqlite3_errmsg(database));

       if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
           sqlite3_bind_int(compiledStatement, 1, customEntity.id);
           sqlite3_bind_int(compiledStatement, 2, customEntity.type);
           sqlite3_bind_int64(compiledStatement, 3, customEntity.timestamp);
           sqlite3_bind_int(compiledStatement, 4, customEntity.result);
       }

          if(sqlite3_step(compiledStatement) == SQLITE_DONE) {

          }
          else {
             NSLog(@"Step: %d\n", sqlite3_step(compiledStatement));
          }
       }

       sqlite3_finalize(compiledStatement);
   }

   sqlite3_close(database);
} 

I've been doing tests for a while and data was being inserted, but suddenly it stopped to do and I'm now getting a 5 step code at my second NSLog. Why does this happen, if it was working previously? I tried several options I found in some posts, like placing the sqlite3_step(compiledStatement) inside the sqlite3_prepare_v2 but I keep being unable to insert. What I'm doing wrong?

Thanks in advance

Upvotes: 0

Views: 597

Answers (1)

Max
Max

Reputation: 4077

I am not sure but it looks like some of your braces are mis-matched? Anyways, error code 5 indicates that your database is locked.

http://www.sqlite.org/c3ref/c_abort.html

Check if something else is accessing your database ( or your database is not getting closed in some situation in which case your code needs to change). Try the following solution to resolve it :-

sqlite3 database is getting locked

Upvotes: 1

Related Questions