我在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 :(得分:0)
你的代码中没有任何内容跳出来。如果您获得“数据库锁定”,那么这意味着您有一个锁定数据库的打开事务。这可能在您的应用程序中(可能在另一个线程中)或在另一个也访问同一数据库的应用程序中。
答案 1 :(得分:0)
“数据库锁定”表示数据库不可写,这有两个原因 -
1)您忘记完成以前的编译语句或忘记关闭数据库在先前的查询中尝试此操作 -
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);