我不完全了解sqlite3_finalize

时间:2012-04-18 11:12:52

标签: sql ios sqlite

我不完全了解sqlite3_finalize。我的初始代码。

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);

我添加了sqlite3_finalize函数。请检查我。

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);

1 个答案:

答案 0 :(得分:6)

sqlite3_finalizesqlite3_prepare_v2相反。所以你的代码应该是这样的:

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

您不希望为必要的语句做好准备。