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");
}
}

}

tips & tricks

Join 7,719 other subscribers

interview questions


Algorithm Android Android Studio API APP Programming Apps blogging Browser CheatSheets Code Config CSS DATABASE dsa error Features HTML HTML5 IDE installation Interview Questions IOS iPhone javascript Mac objective-c OneDrive OS Placeholder Programming quicktips SDK SEO Settings SMO SQL swift swiftUI Teams Tips & Tricks Tools UI Web Wordpress Xcode


Archives

One response to “How to Insert Value into SqliteDB from NSDictionary in IOS !”

  1. What is SQLite.? – MyCodeTips

    […] SQLite is a public-domain software package that provides RDBMS(Relational Database Management System) […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from CODE t!ps

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

Continue reading