简体   繁体   中英

Why I am getting sqlite3error?

I am trying to reuse an sqlite statement in my application in a method. Here's the relevant code

if(getsets_statement == nil){
    const char *sql = "SELECT DISTINCT num,roll FROM mytable WHERE cls like ? and divname like ?";
    if(sqlite3_prepare_v2(database, sql, -1, &getsets_statement, NULL) != SQLITE_OK){
        NSAssert1(0, @"Error: Failed to prepare stmt with message '%s'", sqlite3_errmsg(database));
    }       
}

sqlite3_bind_text(getsets_statement, 1, [cls UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(getsets_statement, 2, [divname UTF8String], -1, SQLITE_TRANSIENT);

while(sqlite3_step(getsets_statement) == SQLITE_ROW){

    setNumber= sqlite3_column_int(getsets_statement, 0);        

    roll = sqlite3_column_int(getsets_statement, 1);

    [numArr addObject:[NSNumber numberWithInt:setNumber]];
    [rollArr addObject:[NSNumber numberWithInt:roll]];
}

sqlite3_reset(getsets_statement);

The statement executes perfectly the first time it is called. But the next time I call this method, I get a sqlite3error . The values of divname and cls are present (did an NSLog and checked) but I don't understand why I am getting this error. I get the error at the first bind_text statement.

This is in the gdb console

Program received signal:  “EXC_BAD_ACCESS”.
(gdb) where
#0  0x9041857f in sqlite3Error ()
#1  0x9041acea in vdbeUnbind ()
#2  0x9041b2c8 in bindText ()

Any help?

Make sure nothing else is actually the issue (is the database being closed somewhere else? Is the getsets_statement pointing to the same object? Has it been finalized?). Then try using NULL or SQLITE___STATIC instead of SQLITE_TRANSIENT. Since [NSString UTF8String] returns data that doesn't need to be freed (by you), it obviously doesn't need a destructor, and it will stay valid until after your function exits, at which time you're done running the statement anyway.

I believe you need to call sqlite3_reset and sqlite3_clear_bindings on the prepared statement before attempting to reuse it. Also, you should really check your return codes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM