从应用程序执行SQLite命令时出错

时间:2011-09-13 17:42:44

标签: iphone sqlite

我的应用程序中有这个简单的功能:

-(NSMutableArray *)SelectProductID:(NSMutableArray *)arr
{
    NSLog(@"----------------");

    sqlite3_stmt *statement;

    NSMutableArray *arrPordID = [[NSMutableArray alloc]init];

    @try
    {

        //Get productID
        for(NSString *strSubProductID in arr)
        {


            NSString *s = [NSString stringWithFormat:@"SELECT ProductID FROM SubProducttable where SubProductID=%@",strSubProductID];

            const char *sql = [s cStringUsingEncoding:NSASCIIStringEncoding];

            if (sqlite3_prepare_v2(database, [s cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK) {

                while (sqlite3_step(statement) == SQLITE_ROW){

                    char *dbString;

                    dbString = (char *)sqlite3_column_text(statement, 0);
                    NSString *pID = (dbString) ? [NSString stringWithUTF8String:dbString] : @"";
                    [arrPordID addObject:pID];

                }

            }             

        }
    }
    @catch (NSException *exception) {

        @throw exception;
    }
    @finally {

        sqlite3_finalize(statement);
    }
    return arrPordID;

}

我在这里遇到一个奇怪的问题。当应用程序到达while (sqlite3_step(statement) == SQLITE_ROW){时,永远不会输入循环。我不知道为什么。我在SQLite管理器中执行了相同的查询(当应用程序未运行时)。我得到的结果是单一的。我得到的结果是 2 。但在这里我一无所获。

是的,每当我运行我的应用程序时,我总是在SQLite管理器中关闭数据库。我还清理了应用程序,重新启动了XCode,并从模拟器中删除了应用程序。但没有成功。

我在调试过程中也看到了一件奇怪的事情。在调试时,始终会跳过sqlite3_stmt *statement。这是我没有得到任何结果的原因吗?

2 个答案:

答案 0 :(得分:1)

您是否在单引号中尝试过subproductId?

NSString *s = [NSString stringWithFormat:@"SELECT ProductID FROM SubProducttable where SubProductID='%@'",strSubProductID];

答案 1 :(得分:0)

if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
    // Setup the SQL Statement and compile it for faster access
    const char *sqlQuery = @"SELECT ProductID FROM SubProducttable where SubProductID=%@",strSubProductID;
    sqlite3_stmt *statement;
    if(sqlite3_prepare_v2(database, statement, -1, &sqlQuery, NULL) == SQLITE_OK) {
        while(sqlite3_step(sqlQuery ) == SQLITE_ROW) {
            // Read the data and add to your array object
        }
    }
    // Release the compiled statement from memory
    sqlite3_finalize(statement);

}
sqlite3_close(database)
相关问题