How to Insert Value into SqliteDB from NSDictionary in IOS !

NSDictionary in IOS

Sometime we get value in the form of Dictionary like from JSON or Xml API.

Below are the following codes which will help you insert data into sqlite database.

Note:Before this add Sqlite framework and import #import <sqlite3.h>.

self.Dict_sample = [NSMutableDictionary dictionary];
[self.Dict_sample setObject: @“SampleText” forKey: @“keyfor1”];
[self.Dict_sample setObject: @“SampleText” forKey: @“keyfor2”];
[self.Dict_sample setObject: @“SampleText” forKey: @“keyfor3”];
[self.Dict_sample setObject: @“SampleText” forKey: @“keyfor4”];
[self.Dict_sample setObject: @“SampleText” forKey: @“keyfor5”];

NSString *docsDir;
NSArray *dirPaths;

// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

docsDir = [dirPaths objectAtIndex:0];


// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @“mySample.db"]];

NSFileManager *filemgr = [NSFileManager defaultManager];

if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];

if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;


for (NSString *skey in self.Dict_sample)
{

NSString *slink = [self.Dict_sample objectForKey:skey];
// do something with (p,m)


const char *sql_stmt2 = [[NSString stringWithFormat:@"insert into sample table (stitle) values ('%@')",skey] UTF8String];

if (sqlite3_exec(contactDB, sql_stmt2, NULL, NULL, &errMsg) != SQLITE_OK)
{
// NSLog(@"DB-INSERT FAILED");//status.text = @"Failed to create table";
}
else
{
// NSLog(@"DB-INSERT SUCCESS");
}
}

}

Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top