user709877
user709877

Reputation: 69

Retrieving the data from database through sqlite in iphone

I am developing an application in iphone to access the database through sqlite. I declared a method to retrieve the data from database. Whether the return type is an NSArray for this method? After the sqlite select statement what should we do to retrieve the data?

I mean after this query.

NSString *selectStmt=[NSString stringWithFormat:@"select * from %@" , tableName];
sqlite3_prepare_v2(db, [selectStmt UTF8STRING] , -1, &statement, NULL);

please help me out.

Upvotes: 1

Views: 291

Answers (3)

Virat Naithani
Virat Naithani

Reputation: 783

const char *sql = "select * from stocks";

sqlite3_stmt *output;

if(sqlite3_prepare_v2(dbase, sql, -1, &output, NULL)==SQLITE_OK)
{
[temp removeAllObjects];
[temp1 removeAllObjects];
while(sqlite3_step(output)==SQLITE_ROW)
{

    NSMutableString *str = [NSString stringWithUTF8String:(char  *)sqlite3_column_text(output, 0)];
    [temp1 addObject:str];
    str = [NSString stringWithUTF8String:(char *)sqlite3_column_text(output, 1)];
    [temp addObject:str];
}

}

Upvotes: 0

Janak Nirmal
Janak Nirmal

Reputation: 22726

const char *sqlStatement = "your query";

if(sqlite3_prepare_v2(database, sqlStatement, -1, &selectStmt, NULL) == SQLITE_OK) 
{
    // Loop through the results and add them to the feeds array
    while(sqlite3_step(selectStmt) == SQLITE_ROW) 
    {
        NSString *stringField = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStmt, 1)];
        NSInteger intField = sqlite3_column_int(selectStmt, 0);
    }
}

sqlite3_finalize(selectStmt);
selectStmt = nil;

This way you need to read from the database. You can manage all those retrieved fields by declaring a Class. e.g if retrieving fields from Login table you can have class as LoginClass with 2 Properties UserName,Password. Create instance of this class and store fields values retrieved from Db and add it to Array and use them any where Like that.

Hope this helps.

Upvotes: 0

Viktor Apoyan
Viktor Apoyan

Reputation: 10755

NSString *selectStmt=[NSString stringWithFormat:@"select * from %@", tableName];

if( sqlite3_prepare_v2(db, [selectStmt UTF8STRING] , -1,&statement, NULL) == SQLITE_OK ) {
while( sqlite3_step(statement) == SQLITE_ROW ) {

 } 
  }

Here in while you can get data from sqlite and add it to array !!!

Good luck !!!

Upvotes: 1

Related Questions