user1486548
user1486548

Reputation: 1201

iOS & SQLite: How to store database entry as NSString variable

I am completely new to programming of any sort, and have managed to learn enough Obj-C and C over the past month to write a functioning app. However, I have just one problem remaining before my app is complete. I have data stored in an sqlite database that I need to use in my app. I will need to be able to select data from the database and store it as an NSString variable so that it can be used in my app's output.

I have searched through many tutorials, but have found most of them geared toward creating a database within the app and altering its contents. I simply need to call the information and store it as a variable.

Any links to related tutorials would be appreciated, as well as any advice.

Upvotes: 1

Views: 1527

Answers (1)

Chris DeSalvo
Chris DeSalvo

Reputation: 913

Assuming you've stored your strings in the sqlite db as utf-8 data you would extract it from your query result and make an NSString like this:

#import <sqlite3.h>

// Open the db
sqlite3 *db;
int result = sqlite3_open("path/to/your/db", &db);

// Prepare your query
sqlite3_stmt *statement;
result = sqlite3_prepare_v2(db, "select * from table where...;", -1, &statement, NULL);

// Process each row of the response
while (SQLITE_ROW == ((result = sqlite3_step(statement))))
{
    NSString *string = @"";

    // Pull out a given column as a text result
    char *c = sqlite3_column_text(statement, yourStringColumnIndex);

    // Make an NSString out of it
    if (c)
        string = [NSString stringWithUTF8String:c];

    NSLog(@"%@", string);
}

// Release the prepared statement and close the db
sqlite3_finalize(statement);
sqlite3_close(db);

Obviously you should check the error results and respond appropriately.

Upvotes: 1

Related Questions