1

我在我的应用程序中使用 sqlite 数据库。在我的 sqlite 中存在 10 条记录。我想从这个数据库中读取 4 个数据,并且我想获取这些数据,直到最后一个数据中的 BroID 为 NULL(BroID 是列数据之一)这是我的代码,但我不知道如何在我的代码中使用循环,直到 BroID 成为无效的。

    -(NSMutableArray *)readInformationFromDatabase
    {
        array = [[NSMutableArray alloc] init];

        // Setup the database object
        sqlite3 *database;
        // Open the database from the users filessytem
        if(sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK)
        {
// I want to use loop for certain work!!! (this work is get name from data base until BroID to be NULL )
            NSString *sqlStatement_userInfo =[NSString stringWithFormat:@"Select * from table1"];
                sqlite3_stmt *compiledStatement;
                if(sqlite3_prepare_v2(database, [sqlStatement_userInfo UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
                {
                    // Loop through the results and add them to the feeds array
                    while(sqlite3_step(compiledStatement) == SQLITE_ROW)
                    {
                        // Init the Data Dictionary
                        NSMutableDictionary *_dataDictionary=[[NSMutableDictionary alloc] init];
                        NSString *_userName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
                        [_dataDictionary setObject:[NSString stringWithFormat:@"%@",_userName] forKey:@"Name"];

                        [array addObject:_dataDictionary];
                    }
                }
                else
                {
                    NSLog(@"No Data Found");
                }

请告诉我完成此代码的想法。

4

1 回答 1

1

好的,首先SELECT声明:

  • 将语句从更改为SELECT * ...SELECT colname1, colname2, ...这样您就可以确定返回列的顺序,并且您不必参考架构来找出它们返回的顺序。这实际上节省了时间。
  • BroID必须包含在选择的列中。
  • 您需要一个ORDER BY子句以获得一致的结果。
  • 您可能可以让数据库仅包含 rows WHERE BroID IS NOT NULL,这可能适合您的需求。

如果您仍然需要使用代码来停止获取,那么只需使用以下方法测试NULL BroID列并break退出while循环:

while (sqlite3_step(compiledStatement) == SQLITE_ROW)
{
    // Fetch other columns
    if (sqlite_column_type(compiledStatement, INDEX) == SQLITE_NULL)
        break;
}

INDEX的列索引在哪里BroID

不清楚您是否想要BroID IS NULL结果集中的行;如果您在获取列之前不执行sqlite_column_type()测试,则将其保留如上。

有关详细信息,请参阅参考资料

于 2013-05-18T08:48:06.823 回答