Iphone 如何在objective C中更新SQLite数据库中的表?

Iphone 如何在objective C中更新SQLite数据库中的表?,iphone,objective-c,xcode,sqlite,Iphone,Objective C,Xcode,Sqlite,我在sqlite中手动创建了一个名为“dept”的表,其中包含用户名(作为Varchar)和密码(作为整数) 我使用以下代码更新了一个表 NSString *database2=[[NSBundle mainBundle]pathForResource:@"deptDatabase" ofType:@"sqlite"]; NSString *databasePath2=[NSString stringWithFormat:@"%@",database2]; const char *dbPath

我在sqlite中手动创建了一个名为“dept”的表,其中包含用户名(作为Varchar)和密码(作为整数)

我使用以下代码更新了一个表

NSString *database2=[[NSBundle mainBundle]pathForResource:@"deptDatabase" ofType:@"sqlite"];
NSString *databasePath2=[NSString stringWithFormat:@"%@",database2];

const char *dbPath=[databasePath2 UTF8String];
if (sqlite3_open(dbPath, &dbHandler)==SQLITE_OK) {
    NSLog(@"database Opened");
    const char* updateQuery="update dept set password=1234 where username='suren'";
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(dbHandler, updateQuery, -1, &stmt, NULL)==SQLITE_OK) {
        NSLog(@"Query Executed");
    }
}

sqlite3_close(dbHandler);
但该表似乎没有更新。 谁能告诉我如何通过修改上述代码来更新表格。
提前感谢

您不能更新主捆绑包中的文件,这些文件是只读的

要更改数据库,必须将其复制到文档目录。 并使用文档目录中的数据库,而不是主捆绑包中的数据库。 如果主捆绑包中没有文件,则仅将其用作要复制到文档目录的有效负载文件


为什么要在此处创建新字符串:

NSString *database2=[[NSBundle mainBundle]pathForResource:@"deptDatabase" ofType:@"sqlite"];
NSString *databasePath2=[NSString stringWithFormat:@"%@",database2];

database2
databasePath2
相同。您在此处仅使用了内存。

将文件从捆绑包复制到文档目录

NSString *databaseName = @"YOUR DB NAME WITH EXTENSION";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success=[fileManager fileExistsAtPath:databasePath];

if (!success) {

    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

    // Copy the database from the package to the users filesystem
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];  
}
const char *dbPath=[databasePath UTF8String];
if (sqlite3_open(dbPath, &dbHandler)==SQLITE_OK) {
    NSLog(@"database Opened");
    const char* updateQuery="update dept set password=1234 where username='suren'";
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(dbHandler, updateQuery, -1, &stmt, NULL)==SQLITE_OK) {
        NSLog(@"Query Executed");
    }
}

sqlite3_close(dbHandler);
然后,您可以在path数据库path(documents目录)中工作


希望能有帮助。。快乐编码:)

谢谢……正如您所说,mainBundle中的文件是只读的,解决我的问题的替代方法是什么。我已经编辑了我的答案,以提供建议。将文件复制到文档目录,不要使用主捆绑包中的目录。只需使用主捆绑包中的文件作为有效负载。