2012-06-02 39 views
1

我有一個iPad應用程序正在使用FMDB作爲包裝的SQLite數據庫。我能夠成功地從數據庫查詢數據;但是,當我嘗試使用executeUpdate插入數據時,該方法會正確觸發(即,我沒有收到錯誤,並返回YES),但實際上沒有任何內容插入到數據庫中。我嘗試立即檢索我剛插入的對象,它是空的。我也嘗試查看我插入的表中的行數,並且表是空的。任何想法我做錯了什麼?下面是一些代碼:它處理我所有的數據庫的工作之類的Sqlite數據庫與FMDB包裝不插入數據

--init方法

-(NSString *)getDbPath {  
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     return [documentsDirectory stringByAppendingPathComponent:@"iRecipeBox.db"]; 
    } 

    -(id)init { 
     self = [super init]; 
     if(self) { 
      database = [FMDatabase databaseWithPath:[self getDbPath]]; 
      [database open]; 
     } 

     return self; 
    } 

那些會動我分貝到文檔目錄

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    { 
     // Override point for customization after application launch. 
     NSFileManager *fileManager = [NSFileManager defaultManager]; 
     NSError *error; 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 

     NSString *docsPath = [documentsDirectory stringByAppendingPathComponent:@"iRecipeBox.db"]; 

     if ([fileManager fileExistsAtPath:docsPath] == NO) { 
      NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"iRecipeBox" ofType:@"db"]; 
      [fileManager copyItemAtPath:resourcePath toPath:docsPath error:&error]; 
     } 
     return YES; 

--App委託代碼}

- 將數據插入其中一個表的代碼

recipeID = [NSNumber numberWithInt:newRecipeID]; 
    [database beginTransaction]; 
    NSArray *newRow = [[NSArray alloc] initWithObjects:recipeID,title, description, picFile, prepTime, cookTime, ovenTemp, nil]; 
    NSString *sql = @"insert into recipes (id, name, descr, picFile, prepTime, cookTime, ovenTemp) values (?, ?, ?, ?, ?, ?, ?)"; 
    NSLog(@"Before update, the number of args is %i", [newRow count]); 

    if([database executeUpdate:sql withArgumentsInArray:newRow]) { 
     [database commit]; 
     NSLog(@"the insert worked"); 
    } else { 
     [database rollback]; 
     NSLog(@"the insert failed"); 
    } 

回答

1

[FMDatabase databaseWithPath:]返回一個自動釋放對象,所以如果你不使用ARC,你會想保留這個對象。

在executeUpdate:後面檢查[database lastError],看看它是否說了什麼。

最後 - 如果只使用一個插入事務,則使用事務沒有意義。