在iOS中启动应用程序时如何复制sqlite数据库?

时间:2013-03-19 04:00:04

标签: ios objective-c database sqlite

每次启动应用程序时,我都希望从数据库位置复制我的sqlite数据库,并将最新更新复制到我的iOS应用程序。

有什么办法吗?

6 个答案:

答案 0 :(得分:18)

您可以在appdelegate中添加以下方法

- (void) copyDatabaseIfNeeded {

    //Using NSFileManager we can perform many file system operations.
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;

    NSString *dbPath = [self getDBPath];
    BOOL success = [fileManager fileExistsAtPath:dbPath];

    if(!success) {

       NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"database.sqlite"];
       success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

       if (!success)
          NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}

- (NSString *) getDBPath
{   
    //Search for standard documents using NSSearchPathForDirectoriesInDomains
    //First Param = Searching the documents directory
    //Second Param = Searching the Users directory and not the System
    //Expand any tildes and identify home directories.

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    //NSLog(@"dbpath : %@",documentsDir);
    return [documentsDir stringByAppendingPathComponent:@"database.sqlite"];
}

并使用启动方法调用此方法 [self copyDatabaseIfNeeded]; 希望这会有所帮助。

答案 1 :(得分:4)

在应用程序启动时使用以下代码来处理数据库

在您的appdelegate.m

in

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

  [self getdatabase];

  return YES;
}

并将以下函数添加到您的appdelegate.m

-(void)getdatabase
{
    BOOL success;
    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *DBPath = [pathArray objectAtIndex:0];
    NSString *writableDBPath = @"";
    writableDBPath = [DBPath stringByAppendingPathComponent:@"xyz.sqlite"];
    NSLog(@"writableDBPath:%@",writableDBPath);
    success = [filemanager fileExistsAtPath:writableDBPath];
    if (!success) {
        NSString *defaultDBpath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"xyz.sqlite"];
       success = [filemanager copyItemAtPath:defaultDBpath toPath:writableDBPath error:&error];
       if (!success) {
            NSAssert(0, @"failed to copy database at path with message '%@'.",[error localizedDescription]); 
        }
    }     
    NSLog(@"111writableDBPath:%@",writableDBPath);    
}

答案 2 :(得分:0)

试试这个:

NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *strDocDirectory = [docPath objectAtIndex:0];

    self.strDatabasePath = [strDocDirectory stringByAppendingPathComponent:YOUR_DB];


    NSFileManager *filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: self.strDatabasePath ] == NO)
    {
        const char *dbpath = [self.strDatabasePath UTF8String];
        sqlite3 *contactDB;


        if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS YOUR_Table (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)";

            if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog(@"Failed to create table");
            }

            sqlite3_close(contactDB);

答案 3 :(得分:0)

AppDelegate Class

中尝试此操作

.h文件

@property(nonatomic, retain) NSString *dbPath;

.m文件

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self copyDatabaseIfNeeded];
}
- (void) copyDatabaseIfNeeded
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    dbPath = [self getDBPath];

    BOOL success = [fileManager fileExistsAtPath:dbPath];

    if(!success)
    {
       NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sampleDB.sqlite3"];
       success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
       if (!success)
          NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}

/********* Database Path *********/
- (NSString *) getDBPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentsDir = [paths objectAtIndex:0];

    return [documentsDir stringByAppendingPathComponent:@"sampleDB.sqlite3"];
}

如果在应用程序中找不到任何数据库,它将自动复制。

希望它会帮助你。

感谢。

答案 4 :(得分:0)

-(void)openDatase{  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    NSString *documentsDirectory = [paths objectAtIndex:0];  
    self.databasePath = [documentsDirectory stringByAppendingPathComponent:@"weightCal.sqlite"];  
    if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {  
        NSLog(@"Database Successfully Opened ");  
    } else {   
        NSLog(@"Error in opening database ");  
    }  
}

-(void)dealloc{
    sqlite3_close(database);
    [super dealloc];
}


-(void)copyDatabase {
    BOOL success;
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSError *error;
    NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"test.sqlite"];
    success = [fileManager fileExistsAtPath:writablePath];
    if(success) {
       return;
    }
    NSString *defaultPath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.sqlite"];
    success=[fileManager copyItemAtPath:defaultPath toPath:writablePath error:&error];
    if(!success){
       NSAssert1(0,@"Failed to create writable database file with message '%@' .",[error localizedDescription]);
    }
}

.h中声明以下teo变量:

sqlite3 *database; 
NSString *databasePath;

答案 5 :(得分:0)

在这里是Swift 4

Private Sub PriceTextBox1_AfterUpdate()
    Dim bccs1 As String
    Dim bcce1 As String
    bccs1 = BarcodeStartNumber1TextBox.Text
    bcce1 = BarcodeEndNumber1TextBox.Text
    MsgBox ("Please wait for a few moment while the barcodes are validated.")
    On Error GoTo bccErrorHandler1
    If DescriptionTextBox1.Text = "Deep Penetrating Sealant (DPS)" _
                Or DescriptionTextBox1.Text = "Top Seal (TS)" Then
        Sheets("Inventory Log").Select
        Columns("J:J").Select
        Selection.Find(what:=bccs1, after:=ActiveCell, LookIn:=xlFormulas, _
            lookat:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, MatchByte:=False, SearchFormat:=False).Activate
        Do
            If ActiveCell.Offset(0, 1).Value = "In" Then
                ActiveCell.Offset(1, 0).Select
            ElseIf ActiveCell.Offset(0, 1).Value = "Out" Then
                MsgBox ("Barcode" & ActiveCell.Value & " has already been sold")
                If ActiveCell = bbce1 Then Exit Do
                MsgBox ("The barcode batch " & bccs1 & " to " & bcce1 & _
                    " are available")
            End If
        Loop
    End If
bbccErrorHandler1:
    MsgBox ("The barcode you have entered is invalid. Please check entry.")
    Exit Sub
End Sub