samedi 18 avril 2015

Issues when reading from a database in an iPhone app

I am making an iPhone app for a school project that reads and writes to a database. I have managed to get my code to write to it but it won't read. Below is the code I'm using to read:



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);
}


Here is getWritableDBPath:



-(NSString *) getWritableDBPath {
NSString *myDB = @"appData.db";

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:myDB];

}


The reason it doesn't work is that the sqlite3_prepare_v2 if statement is never satisfied.


When I write to the database I copy it to documents.


I am quite sure the results table exists as I am able to write to it. Here is the original sql statement:



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


I did find a similar question on here but didn't think the answers were that relevant to me.


Thanks for your help.


Aucun commentaire:

Enregistrer un commentaire