Hey guys, I'm just playing around with SQLite so this is new for me. I've got a view in which persons data can be both saved and found. The save-function and find-function work perfectly. Now, I've got a new view with a tableView in it. I want to get all the persons in the contacts-table and fill the list with it.
Untill now, I've got:
-(void)viewWillAppear:(BOOL)animated {
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSLog(@"Opened DB");
NSString *querySQL = [NSString stringWithFormat:@"SELECT name FROM contacts"];
const char *query_stmt = [querySQL UTF8String];
NSLog(@"could not prepare statement: %s\n", sqlite3_errmsg(contactDB));
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
//if (sqlite3_step(query_stmt) == SQLITE_DONE)
{
//NSLog(@"SQLite OK");
NSLog(@"SQLite ok");
//if (sqlite3_step(statement) == SQLITE_ROW)
//{
while(sqlite3_step(statement) == SQLITE_ROW) {
NSLog(@"SQLite ROW");
NSString *person = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[personsList addObject:person];
}
//} else {
// NSLog(@"Emtpy list");
//}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
NSLog(@"Calling reload");
NSLog(@"%@", personsList);
[tabelView reloadData];
}
This is all in viewWillAppear. When the view is loaded and done, the log says:
2011-05-06 10:45:26.976 database[1412:207] Opened DB
2011-05-06 10:45:26.978 database[1412:207] could not prepare statement: not an error
2011-05-06 10:45:26.979 database[1412:207] Calling reload
2011-05-06 10:45:26.979 database[1412:207] (
)
So it seems the statement isn't an error, but sqlite3_prepare_v2
isn't SQL_OK after all. Any help?
EDIT: In the previous view, the statement for creating a person is: @"INSERT INTO CONTACTS (name, address, phone) VALUES (\"%@\", \"%@\", \"%@\")", name.text, address.text, phone.text];
The statement for finding someone is: @"SELECT address, phone FROM contacts WHERE name=\"%@\"", name.text];
These two statements work and the data is displayed.
I used const char *dbpath = [databasePath UTF8String];
, but I forgot to put the following code above it:
// Get the documents directory
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.db"]];
const char *dbpath = [databasePath UTF8String];