2

Possible Duplicate:
Exporting Sqlite table data to csv file programatically - xcode iOS 5 (for an ipad app)

I am developing a simple app. I am using sqlite to save data into a table (locally, in app documents folder). I want to problematically export this table data in a csv file and email it to a person. I mean I want to physically access the csv file after conversion in iPad.... Can anybody give an example application to download? Or the code? Please help

0

1 Answer 1

7

This should give you a good idea. Assuming a table with 2 rows, this code reads all the values in the table and writes them to and NSString, which is then written to a CSV file in the documents directory. Let me know if you need clarification on how to make this code work with your specific project.

    NSString *csv = [[NSString alloc] init];

    sqlite3 *database;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *sqLiteDb
    = [documentsDirectory stringByAppendingPathComponent:@"INSERT_DATABASE_NAME.sqlite3"];


    if(sqlite3_open([sqLiteDb UTF8String], &database) == SQLITE_OK) {
        const char *sqlStatement = [[NSString stringWithFormat:@"SELECT * FROM myTable"] UTF8String];
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {

           while(sqlite3_step(compiledStatement) == SQLITE_ROW) { 
             //this assumes that there are two rows in your database you want to get data from   
             [csv stringByAppendingFormat:@"%@,%@\n", [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)], [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]];
           }

          sqlite3_finalize(compiledStatement);
          sqlite3_close(database);
        }else{
            NSLog(@"database error");
        }
    }

NSError *error = nil;
[csv writeToFile:[documentsDirectory stringByAppendingPathComponent:@"myFile.csv"]
      atomically:YES encoding:NSUTF8StringEncoding error:&error];

[csv release];
Sign up to request clarification or add additional context in comments.

Comments