0

我是 xcode 的新手,我在更新 sqlite 时遇到问题。

读取BioViewController.h

@interface readBioViewController : UIViewController {
    NSString *fav;
}

读取BioViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    fav = @"1";
}

- (IBAction)addFavorito:(id)sender {
    DataDAO *dbCrud = [[DataDAO alloc] init];
    NSLog(@"addFavorito favid '%@'.", fav);
    [dbCrud addFavorito:fav];
}

数据DAO.m

-(void)addFavorito:(NSString *)fav {

    NSFileManager *fileMgr = [NSFileManager defaultManager];

    NSString *dirPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"versos.sqlite"];

    BOOL success = [fileMgr fileExistsAtPath:dirPath];

    if(!success) {
        NSLog(@"Cannot locate database file '%@'.", dirPath);
    }

    if(!(sqlite3_open([dirPath UTF8String], &db) == SQLITE_OK)) {
        NSLog(@"An error has occured.");
    }

    NSString *sql = @"update Versos set favorito = 1 Where id = 2";

    char *err;
    if(sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
        sqlite3_close(db);
        NSLog(@"erro no update");
    } else
        NSLog(@"fez o update");
}

我有一个按钮(IBOutlet - addFavorito),我想执行 sql 来更新 ID(2)。我在 NSLog 中看到了结果 "NSLog(@"fez o update");" 但是当我打开 versos.sqlite 时,ID 2 中的结果是 favourito=0 而没有 favourito=1。

4

2 回答 2

2

您无法更新数据库,因为它在您的应用程序包中。您应该先将数据库复制到 Documents 目录,然后修改该文件。

于 2013-06-10T01:12:32.367 回答
0

使用此功能在文档目录中创建数据库。

-(void)CopyDatabaseIfNeeded
{

NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *dbpath=[paths objectAtIndex:0];

dbpath=[dbpath stringByAppendingPathComponent:@"versos.sqlite"];

BOOL success;

NSFileManager *filemanager=[NSFileManager defaultManager];

success=[filemanager fileExistsAtPath:dbpath];

if(success) return;

NSString *dbpathfromapp=[[[NSBundle mainBundle] resourcePath ]   stringByAppendingPathComponent:@"versos.sqlite"];
success=[filemanager copyItemAtPath:dbpathfromapp toPath:dbpath error:nil];
if(!success)
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Error " message:@"failed to Create writable dataBase" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    [alert show];
    [alert release];
}

}

然后用于更新数据库,使用以下函数获取数据库路径/

-(NSString *) GetDatabasePath {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ;
NSString *documentsDirectory = [paths objectAtIndex:0] ;
return [documentsDirectory stringByAppendingPathComponent:@"versos.sqlite"] ;
}
于 2013-06-10T04:46:17.290 回答