iphone - 使用 SQLite for iPhone 从数据库中获取字符串

标签 iphone sqlite

我从教程中获得了这段代码。我想知道如何修改它,以便它不是从数据库中读取 double ,而只是一个字符串。

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 但我不确定如何正确更改参数。

预先感谢您的帮助!

最佳答案

==新更新的答案==

我使用 SQL Lite 的方式与您的使用方式略有不同。我没用过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);

关于iphone - 使用 SQLite for iPhone 从数据库中获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5852117/

相关文章:

iphone - 如何将 SQlite 扩展源文件链接到 iPhone 的 Xcode 中?

android - 从时间戳算起整整几个小时?

mysql - 如何使用 ionic 框架连接sqlite和mysql数据库?

ios - Objective-C,计算一组值的所有可能总和以达到结果目标

iphone - iphone 可以录音吗?

ios - 不可编辑的数据库本地存储在 iOS 应用程序中

ruby-on-rails-3 - 导入 csv 文件后,在我的 sqlite db 表中创建了额外的行

android - 如何从数据库中获取名称?

objective-c - 如何链接 Interface Builder View

iphone - 在对象数组中使用数据