#import #import #include void printUsage() { printf("Usage:csv2sqlite3 INPUT-SQL-FILE DB-NAME INPUT-CSV-FILE\n"); } int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; //read in a csv file... int rows = 0; if (argc < 4) { printUsage(); } else { sqlite3 *db; if (sqlite3_open(argv[1], &db) == SQLITE_OK) { NSString *contents = [NSString stringWithContentsOfFile:[[[NSString alloc] initWithCString:argv[3]] autorelease]]; NSArray *filelines = [contents componentsSeparatedByString:@"\r"]; if (filelines) { for (NSString *line in filelines) { rows++; NSArray *components = [line componentsSeparatedByString:@","]; NSMutableString *compArgs = [[NSMutableString new] autorelease]; [compArgs appendFormat:@"INSERT INTO %s VALUES(", argv[2]]; for (int i = 0; i < [components count]; i++) { //check to remove quotes NSString *val = [components objectAtIndex:i]; if (val && [val length] > 0 && [val characterAtIndex:0] == '"') { NSString *str = [val copy]; while (i < [components count] && [str characterAtIndex:[str length]-1] != '"') { i++; str = [components objectAtIndex:i]; val = [val stringByAppendingString:@","]; val = [val stringByAppendingString:str]; } val = [val stringByReplacingOccurrencesOfString:@"\"" withString:@""]; } val = [val stringByReplacingOccurrencesOfString:@"'" withString:@"''"]; if (i != 0) { [compArgs appendString:@","]; } [compArgs appendFormat:@"'%@'", val]; } [compArgs appendString:@");"]; const char *sql = [compArgs cStringUsingEncoding:NSUTF8StringEncoding]; sqlite3_stmt *statement = nil; if (sqlite3_prepare_v2(db, sql, -1, &statement, NULL) == SQLITE_OK) { sqlite3_step(statement); sqlite3_finalize(statement); NSLog(@"Finalized. Rows=%d", rows); } else { printf("Statement error.\n"); NSLog(compArgs); } } } else { printf("Bad csv file input.\n"); } } else { printf("Bad SQL file input.\n"); } } NSLog(@"%d rows successfully entered.", rows); [pool drain]; return 0; }