-(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);)..