How can I read the entire row of data from SQLite with FMDB in iOS dev?

I can read all the column data from code like this ...

FMResultSet *rs = [db executeQuery:@"SELECT Name, Age, FROM PersonList"]; while ([rs next]) { NSString *name = [rs stringForColumn:@"Name"]; int age = [rs intForColumn:@"Age"]; } 

or find some data this way

 NSString *address = [db stringForQuery:@"SELECT Address FROM PersonList WHERE Name = ?",@"John"]; 

But if I want the contents of the array to contain the entire data string (suppose all my string data is a simple string)

how can i achieve this ...?

thank you for your help!

您 也 可以 用 中文 回答 我, 謝謝 您

+4
source share
2 answers

There is a resultDict method defined in the FMResultSet class. I would do it like this:

 FMResultSet *rs = [db executeQuery:@"SELECT Name, Age, FROM PersonList"]; while ([rs next]) { NSLog(@"%@", [[rs resultDict] description]); } 

This should print something like:

 { Name = bbbbbird1; Age = 25; } 

for each row of the PersonList table. Now there are two ways to enter these values ​​into an array. One of them is to use the allValues ​​NSDictionary method, however, the column order is likely to be upset. Another way is to build the array yourself:

 FMResultSet *rs = [db executeQuery:@"SELECT Name, Age, FROM PersonList"]; while ([rs next]) { NSMutableArray* rowData = [[NSMutableArray alloc] init]; for(int i=0; i<[s columnCount]; i++) { [rowData addObject:[[rs resultDict] objectForKey:[[rs columnNameForIndex:i] lowercaseString]]; } NSLog(@"%@", [rowData description]); } 

The above should print:

 ( bbbbbird1, 25 ) 

Hope this is what you are looking for. You can put this code in the FMResultsSet category if you need to have strings as arrays in many places in your application.

+6
source

The accepted answer is great, but there is an elegant way to achieve the example that the OP gave:

 FMResultSet *rs = [db executeQuery:customQuery]; while ([rs next]) { NSString* tempName = [rs objectForColumnName:@"someColumnName"]; } 

According to the document objectForColumnName return value:

Either NSNumber, NSString, NSData, or NSNull. If the column was NULL, this returns an [NSNull null] object.

Thus, this can be achieved with a single method (if you know the type of your database).

In addition, if you are looking for a custom array containing class objects, you can combine both of them:

 FMResultSet *rs = [db executeQuery:customQuery]; while ([rs next]) { someCustomClassName *tempClass = [[someCustomClassName alloc] init]; [tempClass setSomePropertyValue:[rs objectForColumnName:@"someColumnName"]; [someArray addObject:tempClass]]; } 
+2
source

Source: https://habr.com/ru/post/1390962/


All Articles