目标c:如何根据主键从sqlite表中获取数据?

时间:2012-09-19 05:14:42

标签: objective-c ios sqlite

假设我有一个名为ABC的表,字段为ABCid,ABCn​​ame,ABCImagePath,ABCSequence。现在这个表包含了40多行。

现在我有一组数字说1,4,5,7,8我希望将这些数字与ABCid进行比较,并根据这些ID获取表ABC中的所有数据。

        + (void) getSelectedData : (int)ABCId
        {   
        NSString *dbPath = [self getDBPath];    
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];     

                if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
                {
                    NSString *query =[NSString stringWithFormat:@"select * from [ABC] where ABCId=%d",ABCId];
                    const char *sql = [query cStringUsingEncoding:NSUTF8StringEncoding];
                            sqlite3_stmt *selectstmt;       

    if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK)
                    {
                        [self getInitialDataToDisplay:dbPath]; 
                        ABC *DataObj = [[ABC alloc] initWithPrimaryKey:ABCId];


                        DataObj.ABCName =    [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
                        ABCImagePath =   [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
                        DataObj.ABCSequence = sqlite3_column_int(selectstmt,8);
                        [appDelegate.arrGetData addObject:DataObj];         }
                    else
                    {
                        NSAssert1(0,@"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
                    }
                    NSLog(@"%d",[appDelegate.DataArrayTrans count]);
                        }
                else
                    sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory. 
}

但是应用程序在if条件下崩溃了。另请注意,我使用pageController中的以下行来从ABC Object文件调用上述函数。

for(int i=0;i<[arrRId count];i++)
{
    [ABC getSelectedData:[[arrRId objectAtIndex:i]integerValue]];
    [arr576576 addObject:[appDelegate.arrGetData valueForKey:@"ABCId"]];
}

请指导我在哪里弄错了。谢谢。

1 个答案:

答案 0 :(得分:0)

你的查询应该像这样从ABC中选择*其中ABCId IN(1,4,5,7,8) 就是这样。