【问题标题】:How to retrieve the data from sqlite and save in array using FMDB如何使用 FMDB 从 sqlite 检索数据并保存在数组中
【发布时间】:2017-06-15 13:50:27
【问题描述】:

我已成功将数据保存在 sqlite db 中,但我无法将这些数据保存在数组中。

- (void) createEventTable {

[self createAndDropTablesWithQuery:[NSString stringWithFormat:@"create table if not exists BEACONDATA (rowID integer primary key AUTOINCREMENT, beaconid text)"]];

}

-(void)insertData:(NSArray *)beacon_data
{
    [self createEventTable];
    
    [instance.database open];
    BOOL isInserted;
    @autoreleasepool
    {
        isInserted=[instance.database executeUpdate:@"insert into BEACONDATA (beaconid) values (?)",[NSString stringWithFormat:@"(%@)",beacon_data]];
    } 

[instance.database close];

if(isInserted)
    NSLog(@"Inserted Successfully");
else
    NSLog(@"Error occurred while inserting");

[self displayData];
 }

 -(void)displayData
{

[instance.database open];


FMResultSet *resultSet=[instance.database executeQuery:@"SELECT * FROM BEACONDATA"];
NSMutableArray *array_lastname=[[NSMutableArray alloc]init];

if(resultSet)
{
    while([resultSet next])
        
     NSLog(@"Beacon data %@",[resultSet stringForColumn:@"beaconid"]);

}

}

输出:

Beacon data (01000444)
Beacon data (01000466)
Beacon data (01000001)
Beacon data (01000468)
Beacon data (01000004)
Beacon data (01000006)
Beacon data (01000003)

如何将这些数据保存在数组中我尝试了很多方法但没有成功,如果您有任何想法,请提供帮助。我是 sqlite 新手。

【问题讨论】:

    标签: ios objective-c sqlite


    【解决方案1】:

    FMResultSet 有实例方法resultDictionary 会给你NSDictionary 的记录。所以你可以在你的数组中添加那个字典的对象。

    NSMutableArray *array = [[NSMutableArray alloc]init];
    if(resultSet) {
    while([resultSet next]) {
        NSDictionary *dict = [resultSet resultDictionary];
        [array addObject:dict];
    
        //Or if you want to add simply `beaconid` to array then it should be simply
        [array addObject: [resultSet stringForColumn:@"beaconid"]];
    }
    

    【讨论】:

    • 感谢回答 NSDictionary *dict=[resultSet resultDictionary];这个字典是 nil;
    • 我已经试过这个 [resultSet stringForColumn:@"beaconid"] 也给 nil。
    • [resultSet stringForColumn:@"beaconid"] && [resultSet resultDictionary] 这两个在可打印的 ns 日志中工作,但不保存在数组中。我听不懂。
    • @amitsrivastava 从你的问题你已经为NSLog(@"Beacon data %@",[resultSet stringForColumn:@"beaconid"]); 添加了控制台输出,它不是零
    • @amitsrivastava 在文件中声明您的数组为实例成员,然后尝试使用它添加对象。
    猜你喜欢
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    • 2012-05-14
    • 2011-09-24
    • 1970-01-01
    • 2021-08-15
    • 2013-06-28
    • 2019-07-03
    相关资源
    最近更新 更多