我正在为一个读写数据库的学校项目制作一个iPhone应用程序。我设法让我的代码写入它但它不会读取。以下是我用来阅读的代码:
NSString * paths=[self getWritableDBPath];
const char *dbpath = [paths UTF8String];
sqlite3_stmt *statement;
static sqlite3 *database = nil;
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: @"SELECT questionright, totalquestions, FROM results", nil];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
//code...
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
这是getWritableDBPath:
-(NSString *) getWritableDBPath {
NSString *myDB = @"appData.db";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:myDB];
}
它不起作用的原因是永远不会满足sqlite3_prepare_v2 if语句。
当我写入数据库时,我将其复制到文档中。
我很确定结果表存在,因为我能够写入它。这是原始的sql语句:
DROP TABLE IF EXISTS "Questions";
CREATE TABLE "Questions" ("QuestionID" INTEGER PRIMARY KEY NOT NULL , "Question" TEXT, "RightAnswer" TEXT, "WrongAnswer1" TEXT, "WrongAnswer2" TEXT, "Done" BOOL, "Catagory" TEXT, "Audio" INTEGER);
DROP TABLE IF EXISTS "Results";
CREATE TABLE "Results" ("ResultID" INTEGER PRIMARY KEY NOT NULL , "QuestionRight" INTEGER, "TotalQuestions" INTEGER, "Catagory" TEXT);
我确实在这里找到了类似的问题,但没想到答案与我有关。
感谢您的帮助。
答案 0 :(得分:0)
如果你需要我的建议,如果你真的不需要,不要直接使用sqlite c库,你可以使用FMDB库并摆脱所有头痛的问题 https://github.com/ccgus/fmdb
你可以像这样做
FMDatabase *db = [FMDatabase databaseWithPath:@"your full db path in documents goes here"];
if (![db open]) {
return;
}
FMResultSet *s = [db executeQuery:@"Your query goes here"];
if ([s next]) {
int totalCount = [s intForColumn:@"totalCount"];
}