所以,我已经为此苦苦思索了大约一个星期。
我正在编写一个 iPhone 应用程序,其中包含一个 sqlite 数据库。我可以打开数据库并从中读取(我通过命令行/终端将一些测试数据放入其中),选择特定数据等。但是,我不能做的是从手机插入数据库。当我执行 sqlite3_exec(...) 时,它返回错误代码 8“尝试写入只读数据库。”
我在这里读到其他问题说我使用的是 Main Bundle 的数据库而不是用户数据库,并且模拟器通常会“让你做”,而在实时设备上你会得到一个错误.好吧,这不是我的情况 - 我在模拟器上运行时遇到此错误。据我所知,我的代码检查数据库与许多其他人推荐的完全一样。
这是我用来验证数据库是否存在的代码,如果不存在,我会复制它:
// initialize db (if not already)
+(void) checkDatabase {
// setup some variables
Boolean success;
dbName = @"daarma.sqlite";
NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES);
// I have tried this with both NSUserDirectory and NSUserDomainMask, desn't seem to make a difference
NSString *documentsDir = [documentPath objectAtIndex:0];
dbPath = [documentsDir stringByAppendingPathComponent:dbName];
// dbPath = [[NSBundle mainBundle] pathForResource:@"daarma" ofType:@"sqlite"];
// check to see if the database already exists
NSFileManager *fm = [NSFileManager defaultManager];
success = [fm fileExistsAtPath:dbPath];
if(success) {
NSLog(@"Database exists, returning.");
return;
}
// if not, we create it
NSLog(@"Creating database in user profile...");
NSString *dbPathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];
[fm copyItemAtPath:dbPathFromApp toPath:dbPath error:nil];
[fm release];
[documentPath release];
[documentsDir release];
}
当我使用这个插入数据时:
sqlite3 *db;
int open = sqlite3_open_v2([dbPath UTF8String], &db, -1, NULL);
if(open == 0) {
NSLog(@"open, inserting");
NSString *sql = [NSString stringWithFormat:@"insert into affiliates values('1','2','3','4','5','6','7','8','9','10','11','12')"];
int exec = sqlite3_exec(db, [sql UTF8String], NULL, NULL, NULL);
NSLog(@"exec = %d",exec);
}
sqlite3_close(db);
exec 返回上述错误代码 8:“尝试写入只读数据库。”
我还尝试了通常的重启、清理项目、重置模拟器数据。我什至进入了我的模拟器目录并手动删除了所有应用程序数据。当我尝试返回时,它发现数据库不存在并将其复制过来,但我仍然遇到该错误。
编辑:
我刚刚注意到,如果我在 checkDatabase 方法中这样做:
NSError *error;
[fm copyItemAtPath:dbPathFromApp toPath:dbPath error:&error];
NSLog(@"error = %@",error);
它会导致模拟器在第一次运行时崩溃(在进行内容重置之后),但之后每次它都会恢复上述错误而不会崩溃。所以也许我的 checkDatabase 方法有问题。 ?? :( 它从不告诉我错误消息的输出。
最佳答案
尝试把open函数改成这个
sqlite3_open_v2([dbPath UTF8String], &db, SQLITE_OPEN_READWRITE , NULL);
或者基本上使用简单的 open 函数
Sqlite3_open([dbPath UTF8String],&db);// this should do the job
希望对您有所帮助:)
关于iphone - iPhone 上的 SQLite3 - 插入返回错误代码 8 尝试写入只读数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8407909/