为什么没有创建数据库? [英] Why a Database hasn't created?

查看:76
本文介绍了为什么没有创建数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在我的应用程序中使用 sqlite3.0 创建一个数据库,但该数据库尚未创建.这是我的代码:

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

我不知道错误是什么?我已经在 ViewDidload() 中实现了代码

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

推荐答案

试着像这样检查你的情况

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

这篇关于为什么没有创建数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆