2016-12-30 42 views
1

我想測試SQL是否返回結果。如果沒有結果,我想發送一條消息。問題是,當我做這個測試時,當我想要執行我的過程時(當發現行時),第一行被跳過。我想知道如何測試sqlite中的compiledStatement是否返回一個答案或不錯過第一行

NSString *selectSQL = [NSString stringWithFormat:@"SELECT z_pk, zpostcode, zname, zfirstname, zstreetname, zstreetnumber, zcity FROM ZTAB_PARTICULIER where UPPER(ZNAME) like \'\%%%@%%\' and ZPOSTCODE like \'\%%%@%%\'", [self.name.text uppercaseString], self.postcode.text]; 

const char *query_stmt = [selectSQL UTF8String]; 

sqlite3_stmt *compiledStatement; 


//Compilation de la requete et verification du succes 
if (sqlite3_prepare_v2(database, query_stmt, -1, &compiledStatement, NULL) == SQLITE_OK) 
{ 
    NSLog(@"Prepare Database OK"); 

    int stat = sqlite3_step(compiledStatement); 
    if (stat == SQLITE_DONE) 
    { 
     NSLog(@"NO ROWS!"); 
    } 
    while (sqlite3_step(compiledStatement) == SQLITE_ROW) 
    { 
    ... 

在此先感謝

+2

不相關,但不要使用'stringWithFormat'將文本值插入到SQL語句中。例如。嘗試搜索「Joe's Bar」的代碼,並且「sqlite3_prepare_v2」將失敗。相反,在SQL (不包括引號)中使用'?'佔位符,並使用['sqlite3_bind_text'](http://sqlite.org/c3ref/bind_blob.html)。或者使用像[FMDB](https://github.com/ccgus/fmdb)這樣的庫來簡化綁定過程。 – Rob

+0

謝謝你的提示,我打算使用它。 :D – Claudio

回答

2

刪除第一次調用sqlite3_step。只需要在while循環中增加一個計數器,並在while循環之後,查看該計數器是否爲零。

例如,你可以這樣做:

if (sqlite3_prepare_v2(database, query_stmt, -1, &compiledStatement, NULL) == SQLITE_OK) { 
    NSLog(@"Prepare Database OK"); 

    // int stat = sqlite3_step(compiledStatement); 
    // if (stat == SQLITE_DONE) 
    // { 
    //  NSLog(@"NO ROWS!"); 
    // } 

    NSInteger rows = 0; 
    int rc; 

    while ((rc = sqlite3_step(compiledStatement)) == SQLITE_ROW) { 
     rows++; 

     ... 
    } 

    if (rc != SQLITE_DONE) { 
     NSLog(@"Some error %s (%ld)", sqlite3_errmsg(), (long)rc); 
    } 

    if (rows == 0) { 
     NSLog(@"NO ROWS!"); 
    } 

    ... 

類似的東西檢查不僅是「無行」的局面,同時也檢查錯誤。

+0

噢好吧,我要去使用它。我相信有一種方法與「SQLITE_DONE」。謝謝。 – Claudio

相關問題