在Objective C中打开和创建SQLite数据库

Mar*_*ten 4 database sqlite objective-c ios

我想开发一个iOS应用程序,所以我正在学习Objective C.我在我的应用程序中遵循了使用SQLite数据库的教程.(http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_7_Application)

我有以下代码用于打开和创建我的数据库,但它不起作用!我收到消息"无法打开或创建数据库".谁能告诉我有什么问题?

- (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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经包含了'libsqlite3.dylib'并将#import添加到了H文件中.

man*_*jmv 7

在你的代码中,有一些错误

// Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
Run Code Online (Sandbox Code Playgroud)

使用NSDocumentDirectory而不是NSDocumentationDirectory

我认为它会解决你的问题.在我的建议中,您可以尝试核心数据.它更简单你可以试试这个教程 http://www.raywenderlich.com/934/core-data-tutorial-for-ios-getting-started

它非常简单易懂.