How to convert SQLite schema to CSV format?

Discussion in 'iOS Programming' started by Narendar Singh, Jul 6, 2012.

  1. Narendar Singh macrumors member

    Narendar Singh

    Joined:
    Jun 22, 2012
    Location:
    INDIA
    #1
    I have few rows in SQLite schema, I want to mail this data in CSV format from my iOS application.

    How can I achieve this?

    FYI my schema has following columns:
    name | dob | mobile_number
     
  2. CodeBreaker macrumors 6502

    Joined:
    Nov 5, 2010
    Location:
    Sea of Tranquility
    #2
    A dumb way would be to have three arrays, one for each column.

    You have to write a SQL query for each column in the table.

    Then you can easily create the CSV string:

    Code:
    NSString *csvString = @"name, dob, mobile_number";
    for (int i = 0; i < totalRows; i++) {
        csvString = [csvString stringByAppendingString:[NSString stringWithFromat:@"\n%@, %@, %@", [names objectAtIndex:i], [dobs objectAtIndex:i], [mobile_numbers objectAtIndex:i]]];
    }
    
     
  3. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #3
    There is an NSArray method that returns all an array's components joined by a given string. If the array held one complete row, and the string is a comma, you'll get CSV (or the simple-minded version of it). The method is componentsJoinedByString:.

    "Simple-minded" means it won't account for quotes or commas in a component string. So if one of the strings in the array was @"Oops, it broke", then you'd end up with a comma where it shouldn't be.

    As with many things in programming, a better CSV generator can be built up from smaller simpler parts. If the OP isn't interested in doing that, then like many things in programming, a little searching can often find someone else's code. For example, google search terms: CSV objective-C or cocoa csv
     
  4. Narendar Singh thread starter macrumors member

    Narendar Singh

    Joined:
    Jun 22, 2012
    Location:
    INDIA

Share This Page