我在ios做一个项目,我有下一个问题: 我正在使用现有的数据库,第一步(打开数据库)工作正常,但是当我尝试读取数据时出错了。
控制台仅显示:2013-02-26 14:46:59.999 MyApp [66537:c07]读取数据的问题
-(void) openDB
{
@try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"data.db"];
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.");
}
}
@catch (NSException *exception) {
NSLog(@"An exception occured: %@", [exception reason]);
}
}
-(void) getData{
NSString *sql = @"SELECT * FROM frases";
sqlite3_stmt * stmt;
if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, nil) != SQLITE_OK) {
NSLog(@"problem reading data");
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self openDB];
[self getData];
}
答案 0 :(得分:-1)
- (void)getData { NSString * sql = @“SELECT * FROM frases”; sqlite3_stmt * stmt;
if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, nil) != SQLITE_OK) {
NSLog(@"problem reading data");
}else{
sqlite3_stmt *compiledstatement;
const char *selectStatement = [sql UTF8String];
sqlite3_prepare_v2(sqlDatabase, selectStatement, -1, &compiledstatement, NULL);
if (sqlite3_step(compiledstatement) == SQLITE_DONE) {}
else NSLog(@"Failed!");
sqlite3_finalize(compiledstatement);
}
}
我就是这样做的。有一个泛型函数,只需传入变量。
-(void)readDB:(NSString *)queryString {
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
strDatabasePath = [NSString stringWithString:[docsDir stringByAppendingPathComponent:@"database.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: strDatabasePath] == YES)
{
const char *dbpath = [strDatabasePath UTF8String];
if (sqlite3_open(dbpath, &sqlDatabase) == SQLITE_OK)
{
const char* beginString = "BEGIN;";
sqlite3_stmt *compiledstatement;
sqlite3_prepare_v2(sqlDatabase, beginString, -1, &compiledstatement, NULL);
if (sqlite3_step(compiledstatement) == SQLITE_DONE) {}
else DLog(@"Failed!");
sqlite3_finalize(compiledstatement);
DLog(@"QUERY : %@",queryString);
const char *selectStatement = [queryString UTF8String];
sqlite3_prepare_v2(sqlDatabase, selectStatement, -1, &compiledstatement, NULL);
//sqlite3_bind_text(compiledstatement,1,[statusString UTF8String],-1,SQLITE_TRANSIENT);
if (sqlite3_step(compiledstatement) == SQLITE_DONE) {}
else DLog(@"Failed!");
sqlite3_finalize(compiledstatement);
const char* endString="END;";
sqlite3_prepare_v2(sqlDatabase, endString, -1, &compiledstatement, NULL);
if (sqlite3_step(compiledstatement) == SQLITE_DONE) {}
else DLog(@"Failed!");
sqlite3_finalize(compiledstatement);
sqlite3_close(sqlDatabase);
}
else DLog(@"Failed to open table");
}
}
NSString *queryString;
queryString = @"SELECT * FROM frases";
[self readDB:queryString];
希望这有帮助...记得关闭数据库(sqlite3_close(sqlDatabase);)..