[英]iOS - FMDB database insert
要使用sqlite將數據插入數據庫,需要復制數據庫以使其可寫。 所以我在課堂上有這個方法,我在堆棧上看到的每個建議都溢出了許多其他網站:
-(void)createEditableCopyOfDatabaseIfNeeded
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
當然我有下一個代碼來訪問我的數據庫:
FMDatabase *db; = [FMDatabase databaseWithPath:[[NSBundle mainBundle] pathForResource:@"sample" ofType:@"db"]];
if (![db open]) {
NSLog(@"Error!");
}
else {
NSLog(@"Database opened!!");
}
[self createEditableCopyOfDatabaseIfNeeded];
[db executeUpdate:@"Insert into user (name, phone, comment) values(?, ?, ?)", @"Name1", @"13548", @"This is a comment", nil];
NSLog(@"Inserted");
FMResultSet *s = [db executeQuery:@"SELECT * FROM user"];
while ([s next]) {
NSLog(@"%@", [s stringForColumn:@"comment"]);
}
現在,我有幾個問題:
執行/運行時,插入代碼在模擬器中完美運行。 但是,這對真正的sample.db沒有影響,我得出結論,它必須在我的mac的硬盤驅動器中有一個可寫副本。 這是可以接受的。 但是當我在iphone上運行這些代碼時,它有點無法識別我的createEditableCopyOfDatabaseIfNeeded
方法並給出了這個錯誤: Unknown error finalizing or resetting statement > (8: attempt to write a readonly database)
。 如何使用FMDB使這些代碼正常工作?
在iPhone上運行時,被復制的數據庫位於何處? 復制后,即使沒有連接到我的Mac,iPhone是否會再次使用該數據庫?
在設備上運行時我無法插入內容。 請幫忙。
非常感謝!
如果你正在閱讀這篇文章,那么我會解釋你的問題。
如果Resource Bundle中有任何文件,則它是READ-ONLY文件。 因此,您的資源目錄的數據庫路徑僅供閱讀之用。
根據您為復制數據庫而編寫的代碼,將在應用程序的文檔目錄中創建數據庫。 即使從Mac上移除iPhone,此路徑也不會受到影響。
試試這個插入數據庫
[db open];
FMResultSet *results = [db executeQueryWithFormat:@"SELECT cms_desc FROM cms_media where cms_name=%@",@"name"];
NSString *str;
while([results next])
{
str=[results stringForColumn:@"cms_desc"];
}
[results close];
[db close];
只需將.sqlite文件拖放到項目中,然后在設備中重置app即可
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.