【问题标题】:Why a Database hasn't created?为什么没有创建数据库?
【发布时间】:2014-09-09 16:06:43
【问题描述】:

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

     // 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() 中实现了代码

【问题讨论】:

  • 什么是 open call 返回。返回时 err!sg 是什么?单步执行代码时会发生什么。这里缺少很多基本信息。
  • 您是否尝试设置断点并逐步跟踪它以查看哪些行未执行以及哪些行可能为空?
  • sqlite3_exec 应该返回一个错误 - 它是什么?
  • 它没有返回任何东西,我用断点检查过,它没有进入if条件语句块
  • @user if 到底是哪个阻塞?

标签: ios objective-c sqlite nsfilemanager


【解决方案1】:

试着像这样检查你的状况

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

【讨论】:

  • 超级!它是用你的努力创造出来的。谢谢各位
猜你喜欢
  • 1970-01-01
  • 2015-06-11
  • 2021-10-27
  • 2017-12-09
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-29
相关资源
最近更新 更多