当这个程序运行此代码连接到SQLite数据库时,它可以通过路径测试,打开数据库,SQL在实际数据库上工作。然后它在尝试执行sqlite3_prepare语句时失败。它以1 - SQL错误或缺少数据库的代码退出。然后它将一直继续执行程序,直到它尝试读取从数据库中获取的数据。它然后失败,因为它从来没有得到任何东西,因为它返回了SQL错误或缺少sqlite3_prepare语句中的数据库代码。我正在寻找错误的代码部分/我可以纠正以使其在sqlite3_prepared语句上成功。
#import "contactDAO.h"
#import "contact.h"
@implementation contactDAO
- (NSMutableArray *) getList{
NSMutableArray *contactArray = [[NSMutableArray alloc] init];
@try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"iFLY.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(@"Cannot locate database file '%@'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(@"An error has occured.");
}
const char *sql = "SELECT reportNumber, dateEntered, country, state FROM CONTACT";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(@"Problem with prepare statement");
}
//
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Contact *contactInfo;
contactInfo.reportNumber = sqlite3_column_int(sqlStatement, 0);
contactInfo.dateEntered = sqlite3_column_int(sqlStatement, 1);
contactInfo.country = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
contactInfo.state = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,3)];
/*contactInfo.county = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,4)];
contactInfo.town = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,5)];
contactInfo.policeContact = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,6)];
contactInfo.policeReport = sqlite3_column_int(sqlStatement, 7);
contactInfo.autopsyNumber = sqlite3_column_int(sqlStatement, 8);
contactInfo.lastSeen = sqlite3_column_int(sqlStatement, 9);
contactInfo.victimName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,10)]; */
[contactArray addObject:contactInfo];
}
}
@catch (NSException *exception) {
NSLog(@"An exception occured: %@", [exception reason]);
}
@finally {
return contactArray;
}
}
@end
谢谢!
答案 0 :(得分:0)
你错过了'db'的声明,如下所示:
sqlite3 *db;
我还可以看到这个问题的清晰度问题:
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
由于您的代码即使在发现问题时也会继续评估内容,因为您不会在尝试捕获错误的部分之后返回。
您的执行顺序应该看起来像这样:
if (sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)
{
const char *sql = "SELECT * FROM table";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, sql, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW) { /* do stuff here */ }
}
}
答案 1 :(得分:0)
联系视图或桌子吗?从视图中选择时,我遇到了类似的错误。当我把它改成桌子时,它起作用了。