在iPhone中创建数据库副本

时间:2011-06-01 09:08:35

标签: iphone sql

任何人都可以帮助我:

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

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

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

  • 我们如何在申请路径中复制包含文件的文件夹?

1 个答案:

答案 0 :(得分:5)

“用于创建数据库副本...”

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