lrb333
lrb333

Reputation: 65

Getting string from database using SQLite for iPhone

I have this code from a tutorial. I'm wondering how to modify it so that it reads not a double from the database, but just a string.

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];
}

I'm pretty sure that the lines that need to be altered are:

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

I'll need to use sqlite3_bind_text and sqlite3_column_text but I'm not sure how to alter the parameters correctly.

Thank you in advance for your help!

Upvotes: 1

Views: 1267

Answers (1)

dredful
dredful

Reputation: 4388

==New Updated Answer==

I use SQL Lite a little differently then you do. I have never used sqlite3_bind_text My suggestion is to replace your segment of code with the segment of code I have provided. I have attempted to make it cover your full section of code. It may need a tweak or two.

The solution below should work across the board with fields and rows. You would only need to use the appropriate sqlite3_column_text, sqlite3_column_double, sqlite3_column_int or other types you may need inside of the while(sqlite3_step(detailStmt) == SQLITE_ROW) loop. If you only need the first row you could change the while loop to 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);

Upvotes: 1

Related Questions