Objective-c inserting data with iphone 4s - iphone

I've made an app in which im using an sqlite database with fmdb wrapper for inserting and consulting data, the data is displayed into a table view, the problem is that when i run the app on an iphone 4 everything works well, but when i do it on an iphone 4s it doesn't..could someone please help me fix this issue.
Here are parts of my code:
Loading DB:
aPools = [[NSMutableArray alloc] init];
NSString *path = [[NSBundle mainBundle] pathForResource:#"poolsDB" ofType:#"sqlite"];
mainDB = [[FMDatabase alloc] initWithPath:path];
[mainDB open];
FMResultSet *fResult = [ mainDB executeQuery:#"SELECT * FROM poolsData"];
while ([fResult next]) {
poolsData = [fResult stringForColumn:#"Name"];
[aPools addObject:poolsData];
}
[mainDB close];
Saving :
-(void) saveIntoDB:(NSString *)name withVolume:(float)volume type:(NSString *)type andDesc:(NSString *)desc {
[mainDB open];
[mainDB executeUpdate:#"INSERT INTO poolsData (Name,Volume,Type,Desc) values (?,?,?,?)",name,
[NSNumber numberWithFloat: volume] ,type,desc, nil];
[mainDB close];
}
Could it be that the table view works in diferent ways beetwen devices?

Try the following code:
for LOADING:
aPools = [[NSMutableArray alloc] init];
NSString *path = [[NSBundle mainBundle] pathForResource:#"poolsDB" ofType:#"sqlite"];
FMDatabase* mainDB = [FMDatabase databaseWithPath:path];
if(![mainDB open])
{
return NO; //since the error in opening database
}
FMResultSet *fResult = [ mainDB executeQuery:#"SELECT * FROM poolsData"];
while ([fResult next]) {
poolsData = [fResult stringForColumn:#"Name"];
[aPools addObject:poolsData];
}
[mainDB close];
code for SAVING:
-(void) saveIntoDB:(NSString *)name withVolume:(float)volume type:(NSString *)type
andDesc:(NSString *)desc {
FMDatabase* mainDB = [FMDatabase databaseWithPath:path];
if(![mainDB open])
{
return; //since the error in opening database
}
[mainDB beginTransaction];
[mainDB executeUpdate:#"INSERT INTO poolsData (Name,Volume,Type,Desc) VALUES
(?,?,?,?)",name,
[NSNumber numberWithFloat: volume] ,type,desc];
[mainDB commit];
[mainDB close];
}

Related

iPhone,FMDatabase : executeQuery not working

Below is the code i am using:
FMDatabaseQueue *queue = [[DataBaseHelper sharedManager] queue];
[queue inDatabase:^(FMDatabase *db) {
FMResultSet *results = [db executeQuery:#"select * from EVENT where ESTATUS='unread' and HIT_ATTEMPTS < 5 "];
if([results next])
{
[results close];
#try {
BOOL success=FALSE;
NSString *query=[NSString stringWithFormat:#"insert into EVENT (EDATA, ESTATUS ,EUSER) values('%#','%#','%#')",#"google.com",#"unread",#"xyz"];
success = [db executeUpdate:query];
NSLog(#"create edata row, %d:%#", [db lastErrorCode], [db lastErrorMessage]);
}
#catch (NSException *exception) {
NSLog(#"Exception");
}
In the above code
success = [db executeUpdate:query]; is not working. I have tried placing breakpoints. After this line of code all exits. None of the logs get printed.
I am not sure why you are using a try and Catch, anywayz follow the steps it will surely work
Creating A Database
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:#"database.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
Opening The Database And Creating Tables(optional)
[database open];
//optional
[database executeUpdate:#"create table user(name text primary key, age int)"];
Querying The Database
FMResultSet *results = [database executeQuery:#"select * from user"];
while([results next]) {
NSString *name = [results stringForColumn:#"name"];
NSInteger age = [results intForColumn:#"age"];
NSLog(#"User: %# - %d",name, age);
}
[database close];

CoreData inserting very huge DB exc_bad_access

I have ~60000 values in my DB.
I must to keep them all. But while inserting values I get exc_bad_access.
Here is my code:
if (context == nil)
{
context = [(radioAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", context);
}
[self performSelectorOnMainThread:#selector(deleteAllFromDB) withObject:nil waitUntilDone:YES];
// here is JSON parsing
int i=0;
#synchronized(self)
{
NSLog(#"Start");
NSEntityDescription *entity = [[NSEntityDescription entityForName:#"Station" inManagedObjectContext:context] autorelease];
for (NSString*string in stations)
{
if (![string isEqualToString:#""])
{
Station*station = [[[Station alloc] initWithEntity:entity insertIntoManagedObjectContext:nil] retain];
NSError *err = nil;
id parsedData = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers error:&err];
if (err) {
NSLog(#"error is %#", [err localizedDescription]);
}
[station setName:[parsedData objectForKey:#"nm"]];
[station setBit: [parsedData objectForKey:#"btr"]];
[station setEnabled: [NSNumber numberWithInt:1]];
//encoding id of the station
scanner = [NSScanner scannerWithString:[parsedData objectForKey:#"id"]];
[scanner scanHexInt:&tempInt];
NSNumber *numb = [[NSNumber alloc]initWithInt:i];
[station setNumber: [NSNumber numberWithInt:[numb intValue]]];
//encoding country ID
numb = [NSNumber numberWithInt:i];
[station setCountryID: [NSNumber numberWithInt:[numb intValue]]];
//encoding genre ID
numb = [NSNumber numberWithInt:i];
[station setGenerID:[NSNumber numberWithInt:[numb intValue]]];
[station setOrder:[NSNumber numberWithInt:i]];
[context insertObject:station];
float k = [stations count];
k = (i + 1)/k;
[self performSelectorOnMainThread:#selector(increaseProgress:) withObject:[NSNumber numberWithFloat:k] waitUntilDone:YES];
i++;
[scanner release];
[numb release];
[station release];
[parsedData release];
}
}
[context save:nil];
[entity release];
NSLog(#"Stop");
NSEntityDescription *entityGen = [NSEntityDescription entityForName:#"Genre" inManagedObjectContext:context];
NSURL* urlForGenre = [NSURL URLWithString:#"xxx.xxx"];
NSData *genres = [[NSData alloc] initWithContentsOfURL:urlForGenre];
NSError *err = nil;
NSArray *parsedGenres = [NSJSONSerialization JSONObjectWithData:genres options:NSJSONReadingMutableContainers error:&err];
if (err)
{
NSLog(#"error is %#", [err localizedDescription]);
}
for (int i =0; i<parsedGenres.count; i++)
{
Genre*gen = [[Genre alloc] initWithEntity:entityGen insertIntoManagedObjectContext:nil];
gen.name = [[parsedGenres objectAtIndex:i] objectForKey:#"nm"];
int tempInt;
NSScanner *scanner= [[NSScanner alloc] init];
scanner = [NSScanner scannerWithString:[[parsedGenres objectAtIndex:i] objectForKey:#"id"]];
[scanner scanInt:&tempInt];
NSNumber *numb = [[NSNumber alloc] init];
numb = [NSNumber numberWithInt:tempInt];
gen.number = [NSNumber numberWithInt:[numb integerValue]];
float k = [parsedGenres count];
k = (i + 1)/k;
[self performSelectorOnMainThread:#selector(increaseProgress:) withObject:[NSNumber numberWithFloat:k] waitUntilDone:YES];
[context insertObject:gen];
[gen release];
}
[entityGen release];
[context save:nil];
NSEntityDescription *entityCon = [NSEntityDescription entityForName:#"Country" inManagedObjectContext:context];
NSURL* urlForCoun = [NSURL URLWithString:#"yyy.yyy"];
NSData *countr = [[NSData alloc] initWithContentsOfURL:urlForCoun];
err = nil;
NSArray *parsedCountr = [NSJSONSerialization JSONObjectWithData:countr options:NSJSONReadingMutableContainers error:&err];
if (err)
{
NSLog(#"error is %#", [err localizedDescription]);
}
NSMutableArray* temp = [[NSMutableArray alloc] init];
for (int i =0; i<parsedCountr.count; i++)
{
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:nil];
countr.name = [[parsedCountr objectAtIndex:i] objectForKey:#"nm"];
int tempInt;
NSScanner *scanner= [[NSScanner alloc] init];
scanner = [NSScanner scannerWithString:[[parsedCountr objectAtIndex:i] objectForKey:#"id"]];
[scanner scanInt:&tempInt];
NSNumber *numb = [[NSNumber alloc] init];
numb = [NSNumber numberWithInt:tempInt];
countr.number = [NSNumber numberWithInt:[numb integerValue]];
[temp addObject:countr];
float k = [parsedCountr count];
k = (i + 1)/k;
[self performSelectorOnMainThread:#selector(increaseProgress:) withObject:[NSNumber numberWithFloat:k] waitUntilDone:YES];
[context insertObject:countr];
[countr release];
}
[context save:nil];
If my app doesn't crash, yes, it happens not by every launch. It crashes on:
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:nil];
Please help! And sorry for my terrible English.
Update:
On:
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:nil];
Thread 7: EXC_BAD_ACCESS (code=1, address=0x3f800008)
Other error is exc_bad_access too. But with code=2 and on other thread.
Update 2:
I enabled zombies mode in scheme of my debug. Nothing happened.
Update 3:
I think I have problems with memory.
GuardMalloc: Failed to VM allocate 4128 bytes
GuardMalloc: Explicitly trapping into debugger!!!
You can't pass nil as managedObjectContext parameter to initWithEntity:insertIntoManagedObjectContext: method. Try changing this:
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:nil];
to this
// pass managed object context parameter
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:context];
Based on the documentation and my experience you can pass nil as managedObjectContext.
I was also getting an EXC_BAD_ACCESS and it came that the reason was that I was not retaining the managed object model(I was only creating a model to get the entity description and then it was released).
In particular, this is what I was doing:
In a test class, in the setUp method:
- (void)setUp
{
[super setUp];
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSURL *modelURL = [bundle URLForResource:#"TestDatamodel" withExtension:#"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
STAssertNotNil(model, nil);
_entity = [[model entitiesByName] objectForKey:NSStringFromClass([MyEntity class])];
STAssertNotNil(_entity, nil);
// ...
}
Then in a test method I was creating a managed object without a context like this:
NSManagedObject *object = [[NSManagedObject alloc] initWithEntity:_entity insertIntoManagedObjectContext:nil];
And I was getting EXC_BAD_ACCESS here.
The solution was to add an ivar to the test class to keep a reference to the managed object model.

Syncing sqlite database with iCloud

I have my sqlite database. now i want syncing with icloud. I read blogs saying sqlite syncing with icloud is not supported. Either go for core data OR "Do what exactly core data does".
Now it is not posible for me to go for core data.So like second option "Do something similar to how CoreData syncs sqlite DBs: send "transaction logs" to iCloud instead and build each local sqlite file off of those."
please can anyone share any sample code for "transaction log" of sqlite OR can expalin in detail stepwise what i need to do?
1) I followed this link to create xml. You can download respective api from its github.Link is - http://arashpayan.com/blog/2009/01/14/apxml-nsxmldocument-substitute-for-iphoneipod-touch/
2) on button click:
-(IBAction) btniCloudPressed:(id)sender
{
// create the document with it’s root element
APDocument *doc = [[APDocument alloc] initWithRootElement:[APElement elementWithName:#"Properties"]];
APElement *rootElement = [doc rootElement]; // retrieves same element we created the line above
NSMutableArray *addrList = [[NSMutableArray alloc] init];
NSString *select_query;
const char *select_stmt;
sqlite3_stmt *compiled_stmt;
if (sqlite3_open([[app getDBPath] UTF8String], &dbconn) == SQLITE_OK)
{
select_query = [NSString stringWithFormat:#"SELECT * FROM Properties"];
select_stmt = [select_query UTF8String];
if(sqlite3_prepare_v2(dbconn, select_stmt, -1, &compiled_stmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(compiled_stmt) == SQLITE_ROW)
{
NSString *addr = [NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,0)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,1)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,2)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,3)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,4)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,5)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,6)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,7)]];
//NSLog(#"%#",addr);
[addrList addObject:addr];
}
sqlite3_finalize(compiled_stmt);
}
else
{
NSLog(#"Error while creating detail view statement. '%s'", sqlite3_errmsg(dbconn));
}
}
for(int i =0 ; i < [addrList count]; i++)
{
NSArray *addr = [[NSArray alloc] initWithArray:[[addrList objectAtIndex:i] componentsSeparatedByString:#"#"]];
APElement *property = [APElement elementWithName:#"Property"];
[property addAttributeNamed:#"id" withValue:[addr objectAtIndex:0]];
[property addAttributeNamed:#"street" withValue:[addr objectAtIndex:1]];
[property addAttributeNamed:#"city" withValue:[addr objectAtIndex:2]];
[property addAttributeNamed:#"state" withValue:[addr objectAtIndex:3]];
[property addAttributeNamed:#"zip" withValue:[addr objectAtIndex:4]];
[property addAttributeNamed:#"status" withValue:[addr objectAtIndex:5]];
[property addAttributeNamed:#"lastupdated" withValue:[addr objectAtIndex:6]];
[property addAttributeNamed:#"deleted" withValue:[addr objectAtIndex:7]];
[rootElement addChild:property];
[property release];
APElement *fullscore = [APElement elementWithName:#"FullScoreReport"];
[property addChild:fullscore];
[fullscore release];
select_query = [NSString stringWithFormat:#"SELECT AnsNo,Answer,AnswerScore,MaxScore,AnsIndex FROM FullScoreReport WHERE Addr_ID = %#",[addr objectAtIndex:0]];
select_stmt = [select_query UTF8String];
if(sqlite3_prepare_v2(dbconn, select_stmt, -1, &compiled_stmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(compiled_stmt) == SQLITE_ROW)
{
APElement *answer = [APElement elementWithName:#"Answer"];
[answer addAttributeNamed:#"AnsNo" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,0)]]];
[answer addAttributeNamed:#"Answer" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,1)]]];
[answer addAttributeNamed:#"AnswerScore" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,2)]]];
[answer addAttributeNamed:#"MaxScore" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,3)]]];
[answer addAttributeNamed:#"AnsIndex" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,4)]]];
[fullscore addChild:answer];
[answer release];
}
sqlite3_finalize(compiled_stmt);
}
}
sqlite3_close(dbconn);
NSString *prettyXML = [doc prettyXML];
NSLog(#"\n\n%#",prettyXML);
//***** PARSE XML FILE *****
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Properties.xml" ];
NSData *file = [NSData dataWithBytes:[prettyXML UTF8String] length:strlen([prettyXML UTF8String])];
[file writeToFile:path atomically:YES];
NSString *fileName = [NSString stringWithFormat:#"Properties.xml"];
NSURL *ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:fileName];
MyDocument *mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
mydoc.xmlContent = prettyXML;
[mydoc saveToURL:[mydoc fileURL]forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
{
if (success)
{
NSLog(#"XML: Synced with icloud");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iCloud Syncing" message:#"Successfully synced with iCloud." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
NSLog(#"XML: Syncing FAILED with icloud");
}];
}
3)MyDocument.h file
#import <UIKit/UIKit.h>
#interface MyDocument : UIDocument
#property (strong) NSString *xmlContent;
#end
4)MyDocument.m file
#import "MyDocument.h"
#implementation MyDocument
#synthesize xmlContent,zipDataContent;
// Called whenever the application reads data from the file system
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
// NSLog(#"* ---> typename: %#",typeName);
self.xmlContent = [[NSString alloc]
initWithBytes:[contents bytes]
length:[contents length]
encoding:NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:#"noteModified" object:self];
return YES;
}
// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
return [NSData dataWithBytes:[self.xmlContent UTF8String] length:[self.xmlContent length]];
}
#end
5) now in ur appdelegate
- (void)loadData:(NSMetadataQuery *)queryData
{
for (NSMetadataItem *item in [queryData results])
{
NSString *filename = [item valueForAttribute:NSMetadataItemDisplayNameKey];
NSNumber *filesize = [item valueForAttribute:NSMetadataItemFSSizeKey];
NSDate *updated = [item valueForAttribute:NSMetadataItemFSContentChangeDateKey];
NSLog(#"%# (%# bytes, updated %#) ", filename, filesize, updated);
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
MyDocument *doc = [[MyDocument alloc] initWithFileURL:url];
if([filename isEqualToString:#"Properties"])
{
[doc openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(#"XML: Success to open from iCloud");
NSData *file = [NSData dataWithContentsOfURL:url];
//NSString *xmlFile = [[NSString alloc] initWithData:file encoding:NSASCIIStringEncoding];
//NSLog(#"%#",xmlFile);
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:file];
[parser setDelegate:self];
[parser parse];
//We hold here until the parser finishes execution
[parser release];
}
else
{
NSLog(#"XML: failed to open from iCloud");
}
}];
}
}
}
6) now in parser method fetch data and insert/update as needed in database.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)nameSpaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqual:#"Property"])
{
NSLog(#"Property attributes : %#|%#|%#|%#|%#|%#|%#|%#", [attributeDict objectForKey:#"id"],[attributeDict objectForKey:#"street"], [attributeDict objectForKey:#"city"], [attributeDict objectForKey:#"state"],[attributeDict objectForKey:#"zip"],[attributeDict objectForKey:#"status"],[attributeDict objectForKey:#"lastupdated"],[attributeDict objectForKey:#"deleted"]);
}
//like this way fetch all data and insert in db
}

How to write and retrieve the sqlite data into the file

Friend it just general question .
How can write and retrieve the data on to the file .And how can make this file in .csv format.
For example i am retrieve data like that
NSString *coords = [[[NSString alloc] initWithFormat:#"%f,%f\n",longitude,latitude] autorelease];
[locations addObject:coords];
Than how can write this data on to the file in .csv format.
And than How can i retrieve this data
To write csv
NSString *coords = [[[NSString alloc] initWithFormat:#"%f,%f\n",longitude,latitude] autorelease];
NSData *csvData = [coords dataUsingEncoding:NSUTF8StringEncoding];
NSArray *UsrDocPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DocsDir = [UsrDocPath objectAtIndex:0];
NSString *csvPath = [DocsDir stringByAppendingPathComponent:#"coords.csv"];
//This is upto your logic that do you want to remove existant csv file or not
BOOL success = [FileManager fileExistsAtPath:csvPath];
if(success){
[FileManager removeItemAtPath:csvPath error:&error];
}
[csvData writeToFile:csvPath atomically:YES];
To read from file
NSData *csvData = [NSData dataWithContentsOfFile:csvPath];
NSString *strCSV = [[NSString alloc]initWithData:csvData encoding:NSUTF8StringEncoding];
Hope it helps
There is a csv parser written by dave delong. you can use that.
First, you'll want to make sure that you're using FMDB to access the database, because people who use the SQLite C API directly in Objective-C are masochists. You can do that like this:
FMDatabase *db = [[FMDatabase alloc] initWithPath:#"/path/to/db/file"];
FMResultSet *results = [db executeQuery:#"SELECT * FROM tableName"];
while([results nextRow]) {
NSDictionary *resultRow = [results resultDict];
NSArray *orderedKeys = [[resultRow allKeys] sortedArrayUsingSelector:#selector(compare:)];
//iterate over the dictionary
}
As for writing to a CSV file, well there's code for that too:
#import "CHCSV.h"
CHCSVWriter * csvWriter = [[CHCSVWriter alloc] initWithCSVFile:#"/path/to/csv/file" atomic:NO];
//write stuff
[csvWriter closeFile];
[csvWriter release];
And to combine them, you'd do:
FMDatabase *db = [[FMDatabase alloc] initWithPath:#"/path/to/db/file"];
if (![db open]) {
//couldn't open the database
[db release];
return nil;
}
FMResultSet *results = [db executeQuery:#"SELECT * FROM tableName"];
CHCSVWriter *csvWriter = [[CHCSVWriter alloc] initWithCSVFile:#"/path/to/csv/file" atomic:NO];
while([results nextRow]) {
NSDictionary *resultRow = [results resultDict];
NSArray *orderedKeys = [[resultRow allKeys] sortedArrayUsingSelector:#selector(compare:)];
//iterate over the dictionary
for (NSString *columnName in orderedKeys) {
id value = [resultRow objectForKey:columnName];
[csvWriter writeField:value];
}
[csvWriter writeLine];
}
[csvWriter closeFile];
[csvWriter release];
[db close];
[db release];
That will write the contents of the tableName table out to a CSV file.
Then you can use CSV Parser to parse the CSV and get data.

How to export SQLite file into CSV file in iPhone SDK

In my app, I want to export a SQLite database file to CSV file..
Could you suggest me how to do this?
Thanks.
First, you'll want to make sure that you're using FMDB to access the database, because people who use the SQLite C API directly in Objective-C are masochists. You can do that like this:
FMDatabase *db = [[FMDatabase alloc] initWithPath:#"/path/to/db/file"];
FMResultSet *results = [db executeQuery:#"SELECT * FROM tableName"];
while([results nextRow]) {
NSDictionary *resultRow = [results resultDict];
NSArray *orderedKeys = [[resultRow allKeys] sortedArrayUsingSelector:#selector(compare:)];
//iterate over the dictionary
}
As for writing to a CSV file, well there's code for that too:
#import "CHCSV.h"
CHCSVWriter * csvWriter = [[CHCSVWriter alloc] initWithCSVFile:#"/path/to/csv/file" atomic:NO];
//write stuff
[csvWriter closeFile];
[csvWriter release];
And to combine them, you'd do:
FMDatabase *db = [[FMDatabase alloc] initWithPath:#"/path/to/db/file"];
if (![db open]) {
//couldn't open the database
[db release];
return nil;
}
FMResultSet *results = [db executeQuery:#"SELECT * FROM tableName"];
CHCSVWriter *csvWriter = [[CHCSVWriter alloc] initWithCSVFile:#"/path/to/csv/file" atomic:NO];
while([results nextRow]) {
NSDictionary *resultRow = [results resultDict];
NSArray *orderedKeys = [[resultRow allKeys] sortedArrayUsingSelector:#selector(compare:)];
//iterate over the dictionary
for (NSString *columnName in orderedKeys) {
id value = [resultRow objectForKey:columnName];
[csvWriter writeField:value];
}
[csvWriter writeLine];
}
[csvWriter closeFile];
[csvWriter release];
[db close];
[db release];
That will write the contents of the tableName table out to a CSV file.
Simply do a SELECT on each table and print out the value of each column as required to a text file.