2012-05-22 48 views
2

我在sqlite中手动创建了一个名为“dept”的表,它具有用户名(如Varchar)和密码(如Integer)。如何更新目标C中SQLite数据库中的表?

我用下面的代码更新表

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

但表似乎没有更新。 任何人都可以请告诉我如何通过更改上面的代码来更新表。 在此先感谢

回答

3

您不能更新mainBundle中的fils,这些文件是只读的。

要更改数据库,您必须将其复制到文档目录。 并在文档目录中使用数据库,而不是主包中的数据库。 如果在那里没有文件,则只使用主包中的一个作为有效载荷文件复制到文档目录。


你为什么在这里新建一个字符串:

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

database2是一样databasePath2。你只是在这里使用内存。从束

+0

谢谢...正如你告诉mainBundle中的文件是只读的,有什么替代方法来解决我的问题。 – surendher

+0

我编辑了我的答案来提出一种方法。将文件复制到文档目录,不要使用主包。只需使用主包中的文件作为有效负载。 – rckoenes

2

将文件复制到文档目录

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]; 
} 

那么在哪里路径databasePath(文档目录)

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

希望它可以帮助工作..快乐编码:)