2011-11-04 16 views
1
NSString *cityInput = cityField.text; 
NSString *code = @""; 
NSString *query = @"SELECT code FROM country WHERE cityname = UPPER(?)"; 
sqlite3_stmt *statement; 
if (sqlite3_prepare_v2(database, [query UTF8String],-1, &statement, nil) == SQLITE_OK) 
{ 
    sqlite3_bind_text(statement, 1, [cityInput UTF8String], -1, SQLITE_STATIC); 
    while(sqlite3_step(statement) == SQLITE_ROW) { 
     code = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]; 
    } 
} 
if(sqlite3_step(statement) != SQLITE_DONE){ 
    NSLog(@"DB: query KO"); 
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"ALERT" message:@"City not found" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; 
    [alertView show]; 
    return; 
} 

sqlite3_close(database); 

兩個問題:源碼得到單列

1)得到單列我必須在循環使用?

2)如果沒有在查詢結果如何警惕「城市找不到」

回答

0
  1. 使用,同時給你的最後一排,並不需要它。將limit 1子句添加到您的查詢中,或者簡單地取第一行返回;
  2. 決定是否通過檢查返回碼來顯示警報。
0

也許兩個答案,

1)沒有,只是if子句會做

2)做一個assignement,然後運行,如果它條款

int result = sqlite3_step(statement) 
    if (result == SQLITE_ROW){ 
     //processline 
    } 
    else{ 
     //show alert 
    } 
1

顯然你會得到最後一行,,

code 

應該是一個數組u聲明可能像這樣

NSMutableArray *code=[NSMutableArray array]; 

然後在while循環使用

[code addobject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]]; 

我希望這是很清楚:)