2011-03-29 110 views
0

我在sqlite中插入第一條記錄,當我試圖添加另一條時,它顯示「Database Locked」錯誤。 代碼是:sqlite中的數據插入問題

- (void) addRecord:(NSMutableDictionary *)recordDict 
{ 

    if(addStmt == nil) { 
     const char *sql = "insert into Product(ProID, BarCode , ProductName) Values(?,?,?)"; 
     if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK) 
      NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database)); 
    } 
    NSInteger recordId = [[recordDict objectForKey:@"ProID"] intValue]; 
    NSLog(@"%d",recordId); 
    sqlite3_bind_int(addStmt, 1,recordId); 
    sqlite3_bind_text(addStmt, 2, [[recordDict objectForKey:@"BarCode"] UTF8String], -1, SQLITE_TRANSIENT); 
    sqlite3_bind_text(addStmt, 3, [[recordDict objectForKey:@"ProductName"] UTF8String], -1, SQLITE_TRANSIENT); 


    if(SQLITE_DONE != sqlite3_step(addStmt)) 
     NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database)); 
    else 
    {//SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid 
     rowID = sqlite3_last_insert_rowid(database); 
     NSLog(@"last inserted rowId = %d",rowID); 

      //Reset the add statement. 
      sqlite3_reset(addStmt); 
    } 
} 
+0

你能格式化你的代碼嗎? – 2011-03-29 09:38:01

+0

使用xcode的目標c – Anand 2011-03-29 09:41:27

回答

0

你的代碼中沒有任何東西會跳出來。如果你得到「數據庫鎖定」,那麼這意味着你有一個打開的數據庫鎖定事務。這可能在您的應用程序(也許在另一個線程中)或另一個也在訪問相同數據庫的應用程序中。

0

「數據庫鎖定」意味着數據庫不可寫,兩方面的原因 -

1)你忘了finlalize以前的編譯陳述或忘記關閉數據庫試試這個在以前的查詢 -

sqlite3_finalize(compiledStatement); 
sqlite3_close(database); 

2)您是否在使用它之前複製Documents目錄中的數據庫?您不能在捆綁包本身中修改數據庫。以下是在文檔目錄中複製數據庫的代碼。

-(void) checkAndCreateDatabase{ 
    // Check if the SQL database has already been saved to the users phone, if not then copy it over 
    BOOL success; 

    // Create a FileManager object, we will use this to check the status 
    // of the database and to copy it over if required 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 

    // Check if the database has already been created in the users filesystem 
    success = [fileManager fileExistsAtPath:databasePath]; 

    // If the database already exists then return without doing anything 
    if(success) return; 

    // If not then proceed to copy the database from the application to the users filesystem 

    // Get the path to the database in the application package 
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName]; 

    // Copy the database from the package to the users filesystem 
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil]; 

    [fileManager release]; 
} 

這裏是如何得到數據庫路徑 -

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDir = [documentPaths objectAtIndex:0]; 
    databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain]; 
    NSLog(@"%@",databasePath);