views:

273

answers:

1

Hi,

I have a sqlite database and I am adding to it new words. The problem is that I can see them added to a table only after restarting application. The "SELECT" statement doesn't "see" newly added elements before restarting application.

Why may this happen?

I am creating some kind of a dictionary. Here is how I add new items:

const char *sql_query = "INSERT INTO words(word) VALUES(?)";
     if(sqlite3_prepare_v2(database, sql_query, -1, &addWordsStmt, NULL) != SQLITE_OK)
     {
      return FALSE;
     }

sqlite3_bind_text(addWordsStmt, 1, [ word UTF8String], -1, SQLITE_TRANSIENT);

    if( sqlite3_step(addWordsStmt) != SQLITE_DONE)
     NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));

sqlite3_reset(addWordsStmt);


sqlite3_finalize(addWordsStmt);

And here is my retrieval code:

const char *sql_query = "SELECT word FROM words WHERE id=?";

     if(sqlite3_prepare_v2(database, sql_query, -1, &getWordsStmt, NULL) != SQLITE_OK) 
     {
      return;
     }

sqlite3_bind_int(getWordsStmt, 1, wordid);

    if( sqlite3_step(getWordsStmt) != SQLITE_ROW)
    {
     NSLog(@"Error while getting data. '%s'", sqlite3_errmsg(database));
     sqlite3_reset(getWordsStmt);
     return;
    }

    NSString *word = [NSString stringWithUTF8String:(char *)sqlite3_column_text(getWordsStmt, 0)];

sqlite3_reset(getWordsStmt);

sqlite3_finalize(getWordsStmt);
+1  A: 

There's your problem:

const char *sql_query = "SELECT word FROM words WHERE id=?";

This isn't how you use SQL. Instead, you should be using SELECT word FROM words; and stepping to get each row as long as you're getting SQLITE_ROW until you get SQLITE_DONE. That will get you all your words. How are you going to find a word by id when you don't know the id of newly added words?

Steven Fisher
Thanks, but I am not sure that it is my problem. I know that id is being auto-increased, so if I have an amount of rows in a table I can get any row I want. That is not what is my problem about. How can I commit changes?
Ilya
Unless the sqlite3_finalize() on your add is being called much later, they're already being committed. Your problem is a misunderstanding of how to get data out of SQLite. How do you count the words? How do you update how many words you expect to have?
Steven Fisher
tewha is correct and his explanation describes why you "see" the data when you restart. Give his explanation a chance.
hyuan
Rereading my last comment, I put an "unless" in there that didn't belong. You don't need to call sqlite3_finalize() to commit a change, that just frees the compiled statement. Commit is automatic regardless of that.
Steven Fisher