Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't fully understand sqlite3_finalize

Tags:

sql

sqlite

ios

I don't fully understand sqlite3_finalize. My initialy code.

while (j < Autors.count)
{
 if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) 
 {
    sqlite3_bind_int(compiledStatement,  1, ((AuthorSettings *)[Autors objectAtIndex:j]).authorId);
    if(sqlite3_step(compiledStatement) != SQLITE_DONE) 
    {    
        NSLog(@"sqlite3_step error %s", sqlite3_errmsg(database));
        sqlite3_busy_timeout(database, 5);
    } 
    else
    {    
        if(sqlite3_prepare_v2(database, sqlStatement_1, -1, &compiledStatement, NULL) == SQLITE_OK) 
        {
            sqlite3_bind_int(compiledStatement,  1, bookId);
            if(sqlite3_step(compiledStatement) != SQLITE_DONE) 
            {    
                NSLog(@"sqlite3_step error %s", sqlite3_errmsg(database));
                sqlite3_busy_timeout(database, 5);
            }    
            else  j++;    
        } 
        else NSLog(@"sqlite3_prepare_v2 error %s", sqlite3_errmsg(database));
    }    
 }
}
sqlite3_finalize(compiledStatement);

I added sqlite3_finalize functions. Please check me.

while (j < Autors.count)
 {
 sqlite3_finalize(compiledStatement); //**added
 if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) 
 {
    sqlite3_bind_int(compiledStatement,  1, ((AuthorSettings *)[Autors objectAtIndex:j]).authorId);
    if(sqlite3_step(compiledStatement) != SQLITE_DONE) 
    {    
        NSLog(@"sqlite3_step error %s", sqlite3_errmsg(database));
        sqlite3_busy_timeout(database, 5);
    } 
    else
    {   
        sqlite3_finalize(compiledStatement); //**added
        if(sqlite3_prepare_v2(database, sqlStatement_1, -1, &compiledStatement, NULL) == SQLITE_OK) 
        {
            sqlite3_bind_int(compiledStatement,  1, bookId);
            if(sqlite3_step(compiledStatement) != SQLITE_DONE) 
            {    
                NSLog(@"sqlite3_step error %s", sqlite3_errmsg(database));
                sqlite3_busy_timeout(database, 5);
            }    
            else  j++;    
        } 
        else NSLog(@"sqlite3_prepare_v2 error %s", sqlite3_errmsg(database));
    }    
 }
}
sqlite3_finalize(compiledStatement);
like image 333
Voloda2 Avatar asked Oct 27 '25 16:10

Voloda2


1 Answers

sqlite3_finalize is the opposite of sqlite3_prepare_v2. So your code should look something like this:

sqlite3_prepare_v2(...);
while () {
  sqlite3_reset(...);
  sqlite3_bind_int(...);
  sqlite3_step(...);
}
sqlite3_finalize(...);

You don't want to prepare you statements more than necessary.

like image 62
Stephen Darlington Avatar answered Oct 30 '25 07:10

Stephen Darlington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!