2011-03-29 112 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);