从SQLite读取 - FMDB - 初学者

时间:2012-03-28 17:52:56

标签: iphone objective-c sqlite fmdb

我正在尝试从数据库文件中读取(执行简单的选择所有函数)。

我正在使用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.我的程序代码与this tutorial.

完全相同

这是代码;

-(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 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,但设法通过正确设置路径来解决这个问题。因此,路径规范中可能存在错误。确保您的数据库路径是完美的。正如大家所说,我建议你使用错误陈述来缩小问题的范围。希望!!

答案 1 :(得分:1)

假设已成功创建数据库并将其导入项目,请尝试以下操作:

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