我是第一次在iPhone上试用SQLite。我面临的错误是下面的ecode中的语句sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK
返回false并且没有显示任何内容。
以下是我的代码:
+ (void) getInitialDataToDisplay:(NSString *)dbPath {
dbTryAppDelegate *appDelegate = (dbTryAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "select name,id from studtry";
sqlite3_stmt *selectstmt;
//below line is never executed and its else part is also not executed.
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
stud *coffeeObj = [[stud alloc] initWithPrimaryKey:primaryKey];
coffeeObj.studName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
//coffeeObj.isDirty = NO;
[appDelegate.studArray addObject:coffeeObj];
// [coffeeObj release];
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
我哪里出错了?我该如何解决?
答案 0 :(得分:0)
检查数据库路径,数据库扩展以及相同的表格&字段。
反正,
使用它而不是直接使用const string ::
NSString *sqlStr = [NSString stringWithFormat:@"select name,id from studtry"];
const char *sql = [sqlStr UTF8String];
while循环结束语句后,
sqlite3_finalize(selectstmt);
然后,在If条件之后,
sqlite3_close(database);
无需写入其他部分。
希望它对你有用。 感谢。
答案 1 :(得分:0)
根据你的代码,所有的东西都是abs正确但我认为你传递错误的DBPath或者可能是db文件不对,请检查这两点
答案 2 :(得分:0)
首先从应用程序&中删除您的应用程序模拟器文件夹。 然后创建名为:: Practise.sqlite3的数据库(SQLite3的类型)
然后编写此方法进行复制:
- (void) copyDatabaseIfNeeded {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Practise.sqlite3"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"Practise.sqlite3"];
}
您可以随时复制,
[self copyDatabaseIfNeeded];
然后,检查您的结果。希望它能起作用。