Cintu
Cintu

Reputation: 913

How to get value by column name and datatype?

for (int i=0; i<sqlite3_column_count(selectStatement); i++)                 
    {
        int intValue = 0;
        const char *strValue;
        switch (sqlite3_column_type(selectStatement,i)) 
        {
        }
}

I'm iterating columns and comparing the type. How can I get the value by specifying datatype and column name to create a dynamic query system? Android equivalent where I have the cursor object globally :

public Object get(String name, QueryDbType type) throws Exception {
        Object retult = null;
        int index = cursor.getColumnIndex(name);
        switch (type) {
        case Text:
            retult = cursor.getString(index);
            break;
        case Int:
            retult = cursor.getInt(index);
            break;
        
        default:
            retult = cursor.getString(index);
            break;
        }
        return retult;
}

Upvotes: 2

Views: 5579

Answers (2)

radical
radical

Reputation: 4424

As far as I know, you can't get the column name -> index mapping. You will have to do it manually. If you have lot of fields, you could build a map/dictionary as follows:

for (int i=0; i<sqlite3_column_count(selectStatement); i++) {
    name = sqlite3_column_name(selectStatement, i);
    // add name to the dictionary 
    dict[name] = i;
}

You can then query the dictionary by name to get the column index. Using the column index you can get the value.

If you don't have a lot of fields, you could just loop and find the index also.

Upvotes: 4

CL.
CL.

Reputation: 180060

Just call the sqlite3_column_* function for the datatype that you want; SQLite will automatically convert the column value to that type, if necessary.

Upvotes: 0

Related Questions