views:

32

answers:

1

I have a table having data.

id type
1  max
1  sam
1  rom
2  jak

I want to retrieve all the type where id=1;

if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                NSString *aRecord = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
                NSLog (@"%@",aRecord);
            }

this statement retrive me only the last record. How can i get all the records?

how to catch these records in the variable. I am using aRecord but it store only last record. So this is the main concern
A: 

The sql ro do this is simply:

select * from <table_name> where id = 1 

do something like this:

NSMutableString *myRecords = [NSMutableString initWithString:@""];

if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {   
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                NSString *aRecord = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];        

                myRecords = [myRecords stringByAppendingString:[NSString stringWithFormat:@"%@ ",arecord]];                
                NSLog (@"%@",aRecord);   
                }   

As Peter Hosey points out in the comments, this will give you one string with all three records separated by a space. You probably want to populate an array with these records instead.

ennuikiller
@ennuikiller,yah, But how to catch these records in the variable. I am using aRecord but it store only last record. So this is the main concern.
alis
see edited answer
ennuikiller
1. That code will probably crash because you never assigned an object's pointer to `myRecords` before the loop, so you're sending `stringByAppendingString:` to a random pointer. 2. Even once you fix that, using `stringByAppendingString:` will simply concatenate all the values together, like “maxsamromjak”. You should use an array here and put the separate string objects into it.
Peter Hosey
@Peter thanks for your comments, edited the answer to correct the errors.
ennuikiller
The NSMutableString class doesn't respond to `initWithString:`, and there's no reason to init with a constant empty string in the first place. You can just use `[[NSMutableString alloc] init]` here. (You also need to release that sooner or later.) But then you're still concatenating into a single string rather than collecting a bunch of strings, one per value.
Peter Hosey
@Peter - yes I know all that .... didnt want to allo-init the NSMutableString since I didn't want to worry about releasing it....also didn't want to write out the code to populate the array, please feel free to do so in your own answer :)
ennuikiller