SQLite3 database doesn't actually insert data - iPhone

前端 未结 3 628
南笙
南笙 2020-12-06 13:18

I\'m trying to add a new entry into my database, but it\'s not working. There are no errors thrown, and the code that is supposed to be executed after the insertion runs, m

相关标签:
3条回答
  • 2020-12-06 13:40

    Make sure you have moved the database to writable directory such as NSDocumentDirectory and NSLibraryDirectory.

    The database file you see in XCode resides in the MainBunble which is readable but not writable.

    You need to add a method to check at runtime if the database exists in your decided (writable) location, if it doesn't exist, use NSFileManager to copy the database file to the writable directory path.

    Here's a snippet from my app Snap-it Notes:

    + (BOOL)createEditableCopyOfDatabaseIfNeeded {
        // First, test for existence.
        BOOL success;
        BOOL newInstallation;
        NSFileManager *fileManager = [[NSFileManager alloc] init];
        NSError *error;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"database_file_path"];
        success = [fileManager fileExistsAtPath:writableDBPath];
        newInstallation = !success;
        if (success) {
            [fileManager release];
            return newInstallation;
        }
        // The writable database does not exist, so copy the default to the appropriate location.
        //NSLog(@"database does not exist");
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"database_file_path"];
        success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
        [fileManager release];
        if (!success) {
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
        }
        return newInstallation;
    }
    
    0 讨论(0)
  • 2020-12-06 13:42

    You should commit the transtaction after the insert using COMMIT; statement.

    0 讨论(0)
  • 2020-12-06 13:54

    Missing semicolon in your SQLite statement?

    NSString *query = [NSString stringWithFormat:@"INSERT INTO lists (name) VALUES('%@')", newField.text];

    I believe it should be:

    NSString *query = [NSString stringWithFormat:@"INSERT INTO lists (name) VALUES('%@');", newField.text];

    Although this might not be your only problem.

    0 讨论(0)
提交回复
热议问题