Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening and creating SQLite database in Objective C

I want to develop an iOS app, so I am learning Objective C. I followed a tutorial for using a SQLite database in my app. (http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_7_Application)

I have the following code for opening and creating of my database, but it doesn't work! I get the message "Failed to open or create database". Can someone tell me what is wrong?

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *docsDir;
    NSArray *dirPaths;

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

    docsDir = dirPaths[0];

    // Build the patht 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 (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT";

            if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
                _lblStatus.text = @"Failed to create table";

            }

            sqlite3_close(_contactDB);
        } else {
            _lblStatus.text = @"Failed to open or create database";
        }
    }
}

I have included 'libsqlite3.dylib' and added #import to the H file.

like image 737
Marten Avatar asked Jan 10 '23 15:01

Marten


1 Answers

In your code, there is some mistake

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

Use NSDocumentDirectory not NSDocumentationDirectory

I think it will solve your problem. In my suggestion, you can try core data. It is more simple You can try this tutorial http://www.raywenderlich.com/934/core-data-tutorial-for-ios-getting-started

It is really simple and easily understandable.

like image 171
manujmv Avatar answered Jan 18 '23 10:01

manujmv