1

Create Database Code

This code is correct. i used that code to create a database it's successful run and created a database but i test my application so i remove or delete my simulator app and again run my application then i see database is not created.

Please tell me what is the actual problem i face.

ClsUpdateNetworkViewController.h

#import <UIKit/UIKit.h>
#import "Person.h"
#import <sqlite3.h>

@interface ClsUpdateNetworkViewController : UIViewController{

   UITextField *name;
   UITextField *phone;
   NSString *databasePath;
   sqlite3 *contactDB;
   int rowcount;

}

@property (nonatomic, strong) Person *person;
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSString *fullName;
@property (nonatomic, strong) NSString *phoneNumber;
@property (nonatomic, strong) NSString *workEmail;

@end

ClsUpdateNetworkViewController.m

 #import "ClsUpdateNetworkViewController.h"
 #import "ClsMainPageAppDelegate.h"
 #import "ClsAddressBookViewController.h"


@interface ClsUpdateNetworkViewController ()

@end

@implementation ClsUpdateNetworkViewController

@synthesize  person,firstName,lastName,fullName,phoneNumber,workEmail;
@synthesize name,phone;

- (void)viewDidLoad
{
   [super viewDidLoad];
// Do any additional setup after loading the view.

   [self createDatabase];
}



-(void) createDatabase
{
   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: @"contacts.db"]];

   NSFileManager *filemgr = [NSFileManager defaultManager];

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

       if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
       {
           char *errMsg;
           const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, PHONE TEXT)";

           if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
           {
               NSLog(@"Failed to create table");

           }

           sqlite3_close(contactDB);

       }
       else
       {
           NSLog(@"Failed to open/create database");

       }
   }

}

i test or debug my application

Code is not going inside this condition.
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
    // inside code is not executed.
}
5
  • You don't need that check at all. If the DB doesn't exist, Sqlite will create it. Otherwise, it will just do nothing since the table already exists. Commented Jul 19, 2013 at 8:49
  • when i insert code in the database i see it's "failed to insert the record in database". when i am not remove that app in simulator it's work is correct but i remove or delete my app in simulator for testing purpose than i see database not to be created or not insert a record. Commented Jul 19, 2013 at 8:58
  • Then you should show the insert part, don't you think? You can easily confirm whether or not it is being created, also, because you can access the files of the iPhone simulator directly. Commented Jul 19, 2013 at 9:01
  • What has debugging shown you? Is docsDir coming back correct (and does it correspond to a real directory on your box)? Is databasePath coming back correct (and ditto)? And where do you open the database if the file DOES exist? Commented Jul 19, 2013 at 11:11
  • I suspect that the problem is that you don't actually open the database in the case where the file exists. Commented Jul 19, 2013 at 11:12

3 Answers 3

1

Call this Function at didFinishLaunchingWithOptions:

-(void)createdb
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"emp.sqlite"];

NSURL *dbURL = [NSURL fileURLWithPath:dbPath];

// copy a database from the bundle if not present
// on disk
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:dbPath])
{
    NSURL *bundlePath = [[NSBundle mainBundle] URLForResource:@"emp" withExtension:@"sqlite"];
    NSError *error = nil;
    if (!bundlePath || ![fm copyItemAtURL:bundlePath toURL:dbURL error:&error]) {
        NSLog(@"error copying database from bundle: %@", error);
    }
}
else
{
    NSLog(@"Success in Copy file");
}
}
Sign up to request clarification or add additional context in comments.

Comments

0

hi try this to create database only just add this code to your file

NSString *databaseName=@"Database.sqlite";

-(void)createDatabaseIfNeeded
{
    //  NSLog(@"Virtual database is created...");
        NSFileManager *fileManager=[[NSFileManager defaultManager]autorelease];
    NSError *error;
    NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *finalPath=[path stringByAppendingPathComponent:databaseName];
    //    NSLog(@"Database Path is:--> %@",finalPath);
    NSString *bundlePath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

    success = [fileManager fileExistsAtPath:finalPath];

    if(success)
    {
        if(sqlite3_open([finalPath UTF8String],&database)!=SQLITE_OK)
        {
            sqlite3_close(database);
        }
        return;
    }
    success=[fileManager copyItemAtPath:bundlePath toPath:finalPath error:&error];

    if(!success)
    {
        NSAssert1(0,@"Failed to create writable database file with message '%@' .",[error localizedDescription]);
    }
    else//First Time Loaded Application....
    {
        if(sqlite3_open([finalPath UTF8String],&database)!=SQLITE_OK)
        {
            sqlite3_close(database);
        }
    }
}

Comments

0

How it worked for me is this

//-----------------------------------------------------------------------------------------------------//
#pragma mark - Shared Instance
//-----------------------------------------------------------------------------------------------------//


+ (SQLConnector *)database
{
    static SQLConnector *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[SQLConnector alloc]init];
    });
    return _sharedClient;
}



//-----------------------------------------------------------------------------------------------------//
#pragma mark - Initialization Methods
//-----------------------------------------------------------------------------------------------------//

- (id)init {
    if ((self = [super init]))
    {
        _databaseName = DB_NAME;

        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [documentPaths objectAtIndex:0];
        _databasePath = [documentsDir stringByAppendingPathComponent:_databaseName];
        NSLog(@"%@",_databasePath);

        if (sqlite3_open([[self dbPath] UTF8String], &_database) != SQLITE_OK)
        {
            [[[UIAlertView alloc]initWithTitle:@"Missing"
                                       message:@"Database file not found"
                                      delegate:nil
                             cancelButtonTitle:@"OK"
                             otherButtonTitles:nil, nil]show];
        }
    }
    return self;
}


- (NSString *)dbPath
{
    [self checkAndCreateDatabase];
    return _databasePath;
}


-(void) checkAndCreateDatabase
{
    // Check if the SQL database has already been saved to the users phone, if not then copy it over
    BOOL success;

    // Create a FileManager object, we will use this to check the status
    // of the database and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Check if the database has already been created in the users filesystem
    success = [fileManager fileExistsAtPath:_databasePath];

    // If the database already exists then return without doing anything
    if(success) return;

    // If not then proceed to copy the database from the application to the users filesystem

    // Get the path to the database in the application package
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:_databaseName];

    // Copy the database from the package to the users filesystem
    [fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:nil];

}




//-----------------------------------------------------------------------------------------------------//
#pragma mark - Helper methods
//-----------------------------------------------------------------------------------------------------//

-(BOOL)dbOpenedSuccessfully
{
    if(sqlite3_open([[self dbPath] UTF8String], &_database) == SQLITE_OK)
    {
        return YES;
    }
    else
    {
        [[[UIAlertView alloc]initWithTitle:@"Error"
                                   message:@"Error on opening the DB"
                                  delegate:self
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil, nil]show];
        return NO;
    }
}






//-----------------------------------------------------------------------------------------------------//
#pragma mark - Query
//-----------------------------------------------------------------------------------------------------//


- (void) executeQuery:(NSString *)strQuery
{
    char *error = NULL;
    if([self dbOpenedSuccessfully])
    {
        NSLog(@"%@",strQuery);
        sqlite3_exec(_database, [strQuery UTF8String], NULL, NULL,&error);
        if (error!=nil) {
            NSLog(@"%s",error);
        }
        sqlite3_close(_database);


    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.