Чтение из SQLite - FMDB - Начинающий - PullRequest
1 голос
/ 28 марта 2012

Я пытаюсь прочитать из файла базы данных (выполняя простой выбор всех функций).

Я использую FMDB.

Вот как я создал БД;

Pro:~ dd$ sqlite3 db.db
SQLite version 3.7.7 2011-06-25 16:35:41
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table cus(id integer primary key, firstname varchar(30));
sqlite> inser into cus(firstname)values('f');
Error: near "inser": syntax error
sqlite> insert into cus(firstname)values('f');
sqlite> select * from cus;
1|f
sqlite> 

Я скопировал файл (db.db) в свою папку ресурсов в xCode.изменил имя файла db на db.db в делегате приложения.Код для моей программы точно такой же, как и в этом руководстве.

Вот код;

-(NSMutableArray *) getCustomers
{
    NSMutableArray *customers = [[NSMutableArray alloc] init];


    NSString * path = [(AppDelegate*)[[UIApplication sharedApplication]delegate]databasePath];
    NSLog(@"DB path %@ ",path);
    FMDatabase *db = [FMDatabase databaseWithPath:path];

    [db open];

    FMResultSet *results = [db executeQuery:@"SELECT * FROM cus"];
     NSLog(@"result %@ ",results);
    while([results next]) 
    {
        NSLog(@"result %@ ",results);
        Customer *customer = [[Customer alloc] init];

        customer.customerId = [results intForColumn:@"id"];
        customer.firstName = [results stringForColumn:@"firstname"];

        [customers addObject:customer];

    }

    [db close];

    return customers; 

}

Моя проблема;

Даже если есть 1запись в БД, результатом оператора Select будет NULL.Почему это так и как я могу это исправить?

Ответы [ 2 ]

1 голос
/ 28 августа 2012

Предполагая, что база данных была успешно создана и импортирована в проект, попробуйте следующее:

-(NSMutableArray *) getCustomers
{
 NSMutableArray *customers = [[NSMutableArray alloc] init];
 NSString * path = [(AppDelegate*)[[UIApplication sharedApplication]delegate]databasePath];
 NSLog(@"DB path %@ ",path);
 FMDatabase *db = [FMDatabase databaseWithPath:path];

 if(![db open])
 {
   NSLog(@"Could not open DB, try again");
   return nil;
 }

 FMResultSet *results = nil;
 results = [db executeQuery:@"SELECT * FROM cus"];
 NSLog(@"result %@ ",results);
 while([results next]) 
 {
   Customer *customer = [[Customer alloc] init];

   customer.customerId = [results intForColumn:@"id"];
   customer.firstName = [results stringForColumn:@"firstname"];

   NSLog(@"Customer object %@", customer);
   [customers addObject:customer];
   [customer release];
 }

 [db close];

 return customers; 
}
1 голос
/ 05 августа 2012

У меня была такая же проблема, но мне удалось ее решить, правильно указав путь.Таким образом, в спецификации пути может быть что-то не так.Убедитесь, что ваш путь к базе данных идеален.И как все предлагают, я рекомендую вам использовать сообщения об ошибках, чтобы сузить проблему.Желает !!

...