2012-03-28 74 views
1

我想從數據庫文件讀取(執行一個簡單的選擇所有功能)。從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。這是爲什麼,我該如何糾正它?

+1

你能多一個參數,執行查詢**錯誤**從https://github.com/聲明ccgus/fmdb執行查詢返回FMResultSet對象,如果成功,則失敗。像執行更新一樣,有一個接受NSError **參數的變體。否則,您應該使用-lastErrorMessage和-lastErrorCode方法來確定查詢失敗的原因。 – 2012-03-28 18:09:18

+0

我同意。使用lastErrorMessage/Code查看數據庫的問題。你還應該檢查數據庫是否被創建,而不是將executeQuery發送給一個無對象。路徑可能不正確。 – Eugene 2012-03-28 19:37:30

+0

我應該在哪裏得到這段代碼,你能幫我編輯我的代碼嗎? – Illep 2012-03-28 23:57:09

回答

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; 
} 
+0

用於提取數據的代碼是正確的,如果仍然存在問題,則可能是數據庫的路徑不正確。 – 2012-08-28 05:17:12

1

我有這個相同的問題,但設法通過正確設置路徑來解決這個問題。所以,在路徑規範中可能會出現問題。確保你的數據庫路徑是完美的。正如大家所建議的那樣,我建議您使用錯誤語句來縮小問題的範圍。祝願!