Search code examples
iosobjective-csqlitensfilemanager

Why a Database hasn't created?


I've tried to create a Database using sqlite3.0 in my app, but the database hasn't created. Here is my code:

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

    docsDir = dirPaths[0];

    // Built the path to the database file
    _databasePath = [[NSString alloc]
                     initWithString: [docsDir stringByAppendingPathComponent:
                                      @"contacts1.db"]];//here the database name is contacts1.db.

    NSFileManager *filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: _databasePath ] == NO)//checking Database exists
    {
        const char *dbpath = [_databasePath UTF8String];

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

            if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
            }
            sqlite3_close(_contactDB);
        } 
    }

I don't what is the error?I've implemented the code in the ViewDidload()


Solution

  • try to check your condition like this

    NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *doctumentsDirectory = [directories lastObject];
        self.databasePath = [[NSString alloc] initWithString:[doctumentsDirectory stringByAppendingPathComponent:@"/contacts1.db"]];
    
        NSFileManager *fileManager = [NSFileManager defaultManager];
    
    
        if (![filemgr fileExistsAtPath: _databasePath ])//checking Database exists
            {
                const char *dbpath = [_databasePath UTF8String];
    
                if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
                {
                    char *errMsg;
                    const char *sql_stmt =
                    "CREATE TABLE IF NOT EXISTS CONTACTS1 (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
    
                    if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
                    {
                    }
                    sqlite3_close(_contactDB);
                } 
            }