SQLite3 question: accessing by column instead of index?

Member
Posts: 38
Joined: 2008.09
Post: #1
I have written some code to access variables from a table, so I do something like the following...
Code:
const char *sql = "SELECT v1, v2, v3 WHERE pk=1";
sqlite3_prepare_v2(database, sql, -1, &init_statement, NULL);
self.myV1 = sqlite3_column_int(init_statement, 0);
self.myV2 = sqlite3_column_int(init_statement, 1);
self.myV3 = sqlite3_column_int(init_statement, 2);

However I would like to do something like this...
Code:
const char *sql = "SELECT * WHERE pk=1";
sqlite3_prepare_v2(database, sql, -1, &init_statement, NULL);
self.myV3 = sqlite3_column_int(init_statement, "v3");
self.myV1 = sqlite3_column_int(init_statement, "v1");
self.myV2 = sqlite3_column_int(init_statement, "v2");

Obviously the code doesnt work, but I want to 1) write my SQL query so I dont have to list all of the tables in the field. 2) I dont want to have to access the fields by column index, I want to access them by column name.

Is this possible in SQLite?
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #2
yes, backwards from what you are expecting:

Code:
int sqlite3_column_count(sqlite3_stmt *pStmt);
const char *sqlite3_column_name(sqlite3_stmt*, int N);
Quote this message in a reply
Member
Posts: 38
Joined: 2008.09
Post: #3
so would i have to do something like this then?

Code:
int num_fields = sqlite3_column_count(init_statement);
for(index = 0; 0 < num_fields; index++)
{
    const char* field_name = sqlite3_column_name(init_statement, index);
    if ([@"v1" compare: [NSString stringWithUTF8String:field_name]] == 0)
    {
        self.myV1 = sqlite3_column_int(init_statement, index);
    }
    else if ([@"v2" compare: [NSString stringWithUTF8String:field_name]] == 0)
    {
        self.myV2 = sqlite3_column_int(init_statement, index);
    }
    else if ([@"v3" compare: [NSString stringWithUTF8String:field_name]] == 0)
    {
        self.myV3 = sqlite3_column_int(init_statement, index);
    }
}

This wouldn't be very efficient , there has to be a better way. Am I missing something?
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #4
you can store the column indices directly after you prepare the statement, there's no need to do the expensive work during execution.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Generating an Index from a 3d Vector Oddity007 2 2,635 Aug 18, 2009 05:38 PM
Last Post: Oddity007
  Noob: Accessing Structures from Cocoa Classes MikeC 15 7,209 Oct 19, 2007 02:42 PM
Last Post: MikeC
  Accessing an inherited class's variables Tobs_ 22 9,510 Feb 28, 2007 05:26 PM
Last Post: mac_girl
  Accessing Pixel Information Nick 11 4,522 Jun 1, 2005 09:33 PM
Last Post: Andrew
  Accessing the Datafork in Carbon Muffinking 3 4,330 May 15, 2002 10:06 AM
Last Post: wadesworld