gpt4 book ai didi

iphone - sqlite错误数据库被锁定

转载 作者:IT王子 更新时间:2023-10-29 06:30:13 26 4
gpt4 key购买 nike

我正在编写的 iPhone 应用程序中有一个 sqlite 数据库。我在后台线程中运行的以下代码出现错误。在后台线程中,我调用了这个方法:

 - (BOOL) songIsInDatabase:(NSString *)songTitle
{
NSString *docsDir;
NSArray *dirPaths;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];


//Build the path to the database file
NSString *databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"Database.db"]];

const char *dbpath = [databasePath UTF8String];

sqlite3_stmt *statement;

if(sqlite3_open(dbpath, &DB) == SQLITE_OK){

NSString *insertSQL = [NSString stringWithFormat:@"select * from Bpm_Table where song_title = '%@'", songTitle];

const char *insert_stmt = [insertSQL UTF8String];
if(sqlite3_prepare_v2(DB, insert_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
return YES;
break;
}
}else{
NSLog(@"the error is %s", sqlite3_errmsg(DB));
}
sqlite3_finalize(statement);
}

[databasePath release];
return NO;
}

然后我调用这个方法:

- (void) addSongToDatabase: (NSString *) songTitle andBPM: (int)bpm andGenre: (NSString *) genre
{
NSString *docsDir;
NSArray *dirPaths;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];


//Build the path to the database file
NSString *databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"Database.db"]];

const char *dbpath = [databasePath UTF8String];

sqlite3_stmt *statement;

if(sqlite3_open(dbpath, &DB) == SQLITE_OK){

NSString *insertSQL = [NSString stringWithFormat:@"insert or replace into Bpm_Table (song_title, bpm, genre) values (\"%@\", \"%d\", \"%@\")", songTitle, bpm, genre];

const char *insert_stmt = [insertSQL UTF8String];
if(sqlite3_prepare(DB, insert_stmt, -1, &statement, NULL) == SQLITE_OK){
if(sqlite3_step(statement) == SQLITE_DONE)
{

} else {
NSLog(@"error: %s", sqlite3_errmsg(DB));
}
}sqlite3_finalize(statement);
}

[databasePath release];
}

如果我同时运行这两种方法,一个接一个地运行,我会收到一条错误消息,指出数据库已锁定。我在搜索谷歌后添加了 sqlite3_finalize 语句,希望能解决这个问题。如果我注释掉这两种方法中的任何一种,就不会出现此错误。

谁知道这是怎么回事?

最佳答案

使用后必须关闭 sqlite 数据库...所以添加此行 sqlite3_close(DB);就在sqlite3_finalize(statement);之后

更新 -

您在一个 while 循环中返回 YES -

        while (sqlite3_step(statement) == SQLITE_ROW)
{
return YES;
break;
}

所以在这里你既没有完成也没有关闭数据库..如果每次打开它都需要关闭

关于iphone - sqlite错误数据库被锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8853954/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com