I have some problem with reading from sqlite3 database.
-(void) readMessengesFromDatabase {
sqlite3 *database;
messenges = [[NSMutableArray alloc] init];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSLog(@"Connection OK");
const char *sqlStatement = "select * from MessagesData";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) NSLog(@"connect to table OK"); else NSLog(@"connect to table FALSE");
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { //не проходит условие
NSLog(@"Connection to table OK");
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSLog(@"Read rows OK");
NSString *dbMessageID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *dbMessageText = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *dbMessageDate = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *dbMediaOrNot = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
Message *messege = [[Message alloc] initWithName:dbMessageText messageID:dbMessageID messageDate:dbMessageDate mediaOrNot:dbMediaOrNot];
[messenges addObject:messege];
[messege release];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
My first NSLog shows me what connection to database is ok. But next step “select * from MessagesData” and if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) NSLog(@"connect to table OK"); else NSLog(@"connect to table FALSE"); shows me “connect to table FALSE”. Tried select from my database’s table whith Terminal and got error “unable to open database file” . Where is my mistake? I don’t see any problems in my code…
If you print the error code returned by
sqlite3_prepare_v2it will be a lot easier to diagnose the problem. The numeric values can be found on this page.However, if you cannot even select from the database in the
sqlite3command line tool, I suggest you check that the file exists, is readable and in the correct format.Try to reproduce the error in your simulator (failing that, copy the database file to your computer e.g. using Organizer). Try to run the query using
sqlite3(I know you did try that, but make sure you are checking the following).If you are getting the message
Error: file is encrypted or is not a database, it means that the database file is corrupt. If you getError: no such table:, it means your database does not exist, is empty, or simply hasn’t got the table. If you get (as in your question):Error: unable to open database(you get this during the opening of sqlite, not when performing the query), it means that sqlite cannot read the file (for example permissions).