从现有的sqlite.db读取数据正在模拟器上工作但不是实际设备(目标C)

时间:2016-07-04 08:26:44

标签: ios objective-c sqlite

我不知道如何修复此错误,我转到“构建阶段”并将sqlit.db文件添加到Bundle资源但仍然出错。 有没有人解决这个问题?

Click Here to see code

-(void) initDatabase{
    dbName  = @"MBox_karaoke.db";
    BOOL success;
    NSFileManager *fileManager  = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writeableDBPath = [documentsDirectory stringByAppendingPathComponent:dbName];
    success = [fileManager fileExistsAtPath:writeableDBPath];

    if(success){
        return;
    }

    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];

    success = [fileManager copyItemAtPath:defaultDBPath toPath:writeableDBPath error:&error];
    if (!success) {
        // NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
        NSLog(@"Database created failed, %@",[error localizedDescription]);
    }
    else {
        NSLog(@"Database created successfully");
    }
}

3 个答案:

答案 0 :(得分:1)

错误表示未找到资源文件。

确保您已将数据库文件复制到bundle中。将数据库拖动到项目导航器时,请确保已选中“如果需要,请复制项目”。

以下解决方案为我工作。

-(void)initializeDatabase {

    NSError *error;
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [docPaths objectAtIndex:0];
    NSString *docPath = [docDir stringByAppendingPathComponent:@"Test.sqlite"];

    NSString *template_path = [[NSBundle mainBundle] pathForResource:@"Test" ofType:@"sqlite"];

    if (![fm fileExistsAtPath:docPath])
        [fm copyItemAtPath:template_path toPath:docPath error:&error];


    //-====
}

答案 1 :(得分:1)

您的代码是正确的,但有些时间数据库文件没有选择目标成员资格,数据库不会复制您发生此类型错误的路径。

  

首先删除/卸载您的安装应用。

     

请在xcode中选择您的数据库文件,并查看您的目标会员资格是否已选中或取消选中。取消选中选中检查。 (见下图)

     

运行项目模拟器并检查路径中可用的数据库。可用于查看数据库浏览包含的数据库是否正确。

NSLog(“Path:%@”,defaultDBPath);

enter image description here

答案 2 :(得分:0)

我的回答

 + (NSString *)databasePath
 {
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *sql_Path=[paths objectAtIndex:0];

    NSString *dbPath=[sql_Path stringByAppendingPathComponent:@"MBox_karaoke.sqlite"];

    NSFileManager *fileMgr=[NSFileManager defaultManager];
    BOOL success;
    NSError *error;
    success=[fileMgr fileExistsAtPath:dbPath];
    if (!success) 
    {
       NSString *path=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"MBox_karaoke.sqlite"];
      success=[fileMgr copyItemAtPath:path toPath:dbPath error:&error];
    }
    return dbPath;
}

创建表格,此处我的表格名称为帐户

+ (void) createTableForAccount
{
   char *error;
   NSString *filePath =[self databasePath];
   if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
   {
      NSString *strQuery=[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS Account(id TEXT,name TEXT);"];
      sqlite3_exec(database, [strQuery UTF8String], NULL, NULL, &error);
   }
   else
   {
      NSAssert(0, @"Table failed to create");
      NSLog(@"Account Table Not Created");
   }
   sqlite3_close(database);
 }

插入数据

 + (void)insertAccountDetails:(NSString *)id:(NSString *)name
 {
     NSString *dbPath=[self databasePath];
     if(sqlite3_open([dbPath UTF8String],&database)==SQLITE_OK)
     {
       NSString *strQuery = [NSString stringWithFormat:@"INSERT into Account(id,name) values(?,?);"];
       if(sqlite3_prepare_v2(database,[strQuery UTF8String] , -1, &stment, NULL)==SQLITE_OK)
      {
            sqlite3_bind_text(stment, 1, [[self checkEmpty:id] UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(stment, 2, [[self checkEmpty:name] UTF8String] , -1, SQLITE_TRANSIENT);
            sqlite3_step(stment);
            sqlite3_reset(stment);
      }
      sqlite3_finalize(stment);
   }
   sqlite3_close(database);
}

从表中获取或获取数据

+ (void)getAccountDetails
{
  NSString *dbPath = [self databasePath];
  if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
  {
     NSString *query = [NSString stringWithFormat:@"SELECT id,name from Account"];
     if (sqlite3_prepare_v2(database, [query UTF8String], -1, &stment, nil) == SQLITE_OK)
     {
        while (sqlite3_step(stment) == SQLITE_ROW)
        {
            NSString *idString = [[self charToString: (char *)sqlite3_column_text(stment, 0)]base64DecodedString];
            NSString *nameString = [[self charToString: (char *)sqlite3_column_text(stment, 1)]base64DecodedString];
            NSMutableArray *arrayId = [[NSMutableArray alloc]init];
            NSMutableArray *arrayName = [[NSMutableArray alloc]init];
            [arrayId addObject:idString];
            [arrayName addObject:nameString];
          }
          sqlite3_reset(stment);
        }
        sqlite3_finalize(stment);
     }
     sqlite3_close(database);
}

在db insert和fetch中调用的其他方法

插入

+ (NSString *)checkEmpty:(NSString *)check
{
  if([check isEqual:[NSNull null]])
    check = @" ";
  return check;
}

获取方法

+ (NSString*)charToString:(const char*)chart
{
  NSString *string = @" ";
  if(string)
  {
    chart = [self checkEmptyChar:chart];
    string=[NSString stringWithUTF8String:chart];
  }
  return string;
}


 + (const char *)checkEmptyChar:(const char *)check
 {
   NSString *string = @" ";
   if (check == NULL)
     check = [string UTF8String];
   return check;
 }