2011-05-01 59 views
1

我從教程中獲得了這段代碼。我想知道如何修改它,以便它從數據庫中讀取的不是雙精度值,而只是一個字符串。使用SQLite for iPhone從數據庫獲取字符串

if(detailStmt == nil) { 
    const char *sql = "Select price from Coffee Where CoffeeID = ?"; 
    if(sqlite3_prepare_v2(database, sql, -1, &detailStmt, NULL) != SQLITE_OK) 
     NSAssert1(0, @"Error while creating detail view statement. '%s'", sqlite3_errmsg(database)); 
} 

sqlite3_bind_int(detailStmt, 1, coffeeID); 

if(SQLITE_DONE != sqlite3_step(detailStmt)) { 

    //Get the price in a temporary variable. 
    NSDecimalNumber *priceDN = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(detailStmt, 0)]; 

    //Assign the price. The price value will be copied, since the property is declared with "copy" attribute. 
    self.price = priceDN; 

    //Release the temporary variable. Since we created it using alloc, we have own it. 
    [priceDN release]; 
} 

我敢肯定,這需要改變線路是:

sqlite3_bind_int(detailStmt, 1, coffeeID); 
NSDecimalNumber *priceDN = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(detailStmt, 0)]; 

我需要使用sqlite3_bind_text和sqlite3_column_text,但我不知道如何正確地改變參數。

非常感謝您的幫助!

回答

2

==新的更新答==

我使用SQL精簡版有點不同,那麼你做的。我從來沒有使用sqlite3_bind_text我的建議是用我提供的代碼段替換你的代碼段。我試圖讓它覆蓋你的全部代碼。它可能需要調整或兩個。

下面的解決方案應該與字段和行一起工作。您只需要使用適當的sqlite3_column_text,sqlite3_column_double,sqlite3_column_int或您在while(sqlite3_step(detailStmt) == SQLITE_ROW)循環內可能需要的其他類型。如果您只需要第一行,您可以將while循環更改爲if (sqlite3_step(detailStmt) == SQLITE_ROW)

if(detailStmt == nil) { 
     const char *sql = "Select threadtxt from Coffee Where CoffeeID = ?"; 
    }  

    if (sqlite3_prepare_v2(database, sql, -1, &detailStmt, NULL) == SQLITE_OK) 
    { 
     // loop through the results and add them to the array 
     while(sqlite3_step(detailStmt) == SQLITE_ROW) 
     { 
      // read the data from the result row 
      NSString *nameString = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)]; 
      self.threadtxt = nameString; 
     } 
    } else { 
     NSAssert1(0, @"Error while getting the price of coffee. '%s'", sqlite3_errmsg(database)); 
    } 

    // Release the compiled statement from memory 
    sqlite3_finalize(detailStmt); 
+0

非常感謝! – lrb333 2011-05-03 00:12:57

+0

剛剛實現... compileStatement從哪裏來? – lrb333 2011-05-03 01:56:23

+0

非常感謝您的耐心等待!所以我現在正在使用你的代碼的更新版本。 (除了必須將所有內容放在第一個if語句之外,否則它不能識別準備語句中的sql。視圖現在會加載!但是我仍然遇到問題,因爲它應該檢索到的字符串表示爲空。我在NSLOG聲明中看到它甚至沒有進入while循環,你對於什麼錯誤有更多的想法嗎?我真的沒有這方面的經驗,只是想爲項目做好準備。 – lrb333 2011-05-03 23:56:50