【问题标题】:Reading from SQLite - FMDB - Beginner从 SQLite 读取 - FMDB - 初学者
【发布时间】:2012-08-28 13:14:12
【问题描述】:

我正在尝试从数据库文件中读取数据(执行简单的全选功能)。

我正在使用 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; 

}

我的问题;

尽管DB中有1条记录,Select语句的结果是NULL。为什么会这样,我该如何纠正?

【问题讨论】:

  • 你能不能用github.com/ccgus/fmdb的多一个参数error语句执行查询如果成功执行查询返回一个FMResultSet对象,失败则返回nil。与执行更新一样,有一个变体接受 NSError ** 参数。否则,您应该使用 -lastErrorMessage 和 -lastErrorCode 方法来确定查询失败的原因。
  • 我同意。使用 lastErrorMessage/Code 查看您的数据库有什么问题。您还应该检查数据库是否已创建,并且您没有将 executeQuery 发送到 nil 对象。路径可能不正确。
  • 我应该在哪里有这个代码,你能帮我编辑我的代码吗?

标签: iphone objective-c sqlite fmdb


【解决方案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; 
}

【讨论】:

  • 获取数据的代码是正确的,如果还有问题,很可能是数据库路径不对。
【解决方案2】:

我遇到了同样的问题,但通过正确设置路径设法解决了这个问题。因此,路径规范可能有问题。请确保您的数据库路径是完美的。正如大家所建议的那样,我建议您使用错误语句来缩小问题范围。祝福!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 2019-01-22
    • 1970-01-01
    • 2013-01-24
    • 2014-08-27
    相关资源
    最近更新 更多