小编典典

在iPhone中创建数据库副本

sql

谁能帮我:

  • 我们如何创建数据库副本?

  • 我们如何在iPhone中打开该数据库?

  • 如何在应用程序路径中创建文件夹?

  • 我们如何在应用程序路径中复制包含文件的文件夹?


阅读 183

收藏
2021-04-22

共1个答案

小编典典

“用于创建数据库的副本…”

BOOL success;

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *finalPath = [documentPath stringByAppendingPathComponent:@"test.sqlite"];

success = [fileManager fileExistsAtPath:finalPath];

if(success)
{
    NSLog(@"Database Already Created.");
    return;
}

NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.sqlite"];

success = [fileManager copyItemAtPath:defaultPath toPath:finalPath error:&error];

if(success)
{
    NSLog(@"Database Created Successfully.");
}

“对于打开该数据库…”

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *finalPath = [documentPath stringByAppendingPathComponent:@"test.sqlite"];

if(sqlite3_open([finalPath UTF8String], &database) != SQLITE_OK)
{
    sqlite3_close(database);
    NSLog(@"Error to Open Database :- %s",sqlite3_errmsg(database));
}

“用于在应用程序路径中创建文件夹”

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder

NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/FolderName"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
     [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}

“用于在应用程序中复制文件和文件夹”

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder

NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/FolderName"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
    BOOL successs;

    NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Files/FolderName"];

    successs  = [[NSFileManager defaultManager] fileExistsAtPath:defaultPath];

    if(successs)
    {
        NSLog(@"TRUE");
        NSString *strFile = [NSString stringWithFormat:@"%@",dataPath];

        NSLog(@"File :- '%@'",strFile);

        [fileManager copyItemAtPath:defaultPath toPath:strFile error:&error];
    }
    else
        NSLog(@"FALSE");
}
2021-04-22