gpt4 book ai didi

iphone - 从 SQLite 读取 - FMDB - 初学者

转载 作者:行者123 更新时间:2023-12-02 10:40:09 24 4
gpt4 key购买 nike

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

我正在使用 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 中的资源文件夹中。在应用委托(delegate)中将 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 .为什么会这样,我该如何纠正?

最佳答案

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

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

关于iphone - 从 SQLite 读取 - FMDB - 初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9913050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com