问题描述
我使用下面的代码在数据库中插入数据。我正在插入aprox 15000记录,但在245条记录之后它会抛出错误无法打开数据库
I am using below code for inserting data in the database. and i am inserting aprox 15000 records but after 245 records it throws the error "Unable to open database"
+(void)addGeoRegions:(const char *)query geoId:(int)geoId geoFatherId:(int)geoFatherId geoName:(NSString *)geoName
geoTypeRegionId:(NSString *)geoTypeRegionId geoZone:(int)geoZone
{
sqlite3_stmt *dataRows = nil;
@try {
if(sqlite3_open([[self getDBPath] UTF8String],&PatientDatabase) == SQLITE_OK)
{
if (sqlite3_prepare_v2(PatientDatabase, query, -1, &dataRows, NULL)!=SQLITE_OK)
{
NSAssert1(0,@"error while preparing %s",sqlite3_errmsg(PatientDatabase));
}
sqlite3_bind_int(dataRows, 1, geoId);
sqlite3_bind_int(dataRows, 2, geoFatherId);
sqlite3_bind_text(dataRows, 3, [geoName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(dataRows, 4, [geoTypeRegionId UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_int(dataRows, 5, geoZone);
if (SQLITE_DONE!=sqlite3_step(dataRows))
{
char *err;
err=(char *) sqlite3_errmsg(PatientDatabase);
if (err)
sqlite3_free(err);
NSAssert1(0,@"error while inserting geo regions. %s",sqlite3_errmsg(PatientDatabase));
}
}
}
@catch (NSException * e) {
}
@finally
{
sqlite3_close(PatientDatabase);
sqlite3_finalize(dataRows);
PatientDatabase=nil;
}
}
所以任何人都可以建议为什么这个问题就出现了。
so please can any one suggest why this problem is occur.
推荐答案
首先,想想Mark的答案,如果你打开数据库一次,你会获得更好的性能关闭它一次。
Firstly, think about Mark's answer, you'll get better performance if you open the database once and close it once.
无论如何,这是对设计改进的建议。你的代码实际上有什么问题是finally块:
Anyway, that was a suggestion for a design improvement. What is actually wrong in your code is the finally block:
@finally
{
sqlite3_close(PatientDatabase); // will fail!
sqlite3_finalize(dataRows);
PatientDatabase=nil;
}
以下是来自 docs。
Here is the relevant line from the sqlite3_close() docs.
您需要在关闭数据库之前运行finalize。事实上,关闭调用失败,最终得到245个打开的数据库句柄。
You need to run the finalize before closing the database. As things stand, the close call fails and you end up with 245 open database handles.
因此,颠倒两个语句的顺序并检查返回代码失败。
So, reverse the order of the two statements and check your return codes for failure.
顺便说一句,NSAssert不是报告错误的合适方式。抛出异常或返回错误,或只记录它。 NSAssert旨在捕获编程错误。它甚至不会被编译到您的发布代码中。
By the way, NSAssert is not an appropriate way to report errors. Throw an exception or return an error, or just log it. NSAssert is designed to catch programming errors. It won't even be compiled into your release code.
这篇关于无法打开数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!