SQLite C ++ Access columns by name

Is there a way to access SQLite results by column name (like C ++ Map) instead of index number in C / C ++?

For example, SQLite access for Python allows using a dictionary

Results = Query("SELECT * FROM table");
print Results['colname']
print Results['anothercol'] 

      

Any similar methods available in C ++ for the SQLite interface?

0


source to share


3 answers


I'd go with Daniel to the SQLAPI ++ recommendation at www.sqlapi.com - at http://www.sqlapi.com/HowTo/fetch.html you can find a simple example of fetching fields by name. The example is a little verbose, so here's just for code:



void showemps(SAConnection* pconn, int minage)
{
  SACommand cmd(pconn, "select name, age from employees where age>:1");  
  cmd << minage;
  cmd.execute();
  while(cmd.FetchNext()) {
    SAString sName = cmd.Field("name");
    long nAge = cmd.Field("age");
    printf("Name: %s, age: %d \n", sName, nAge);
  }
}

      

+2


source


newer answer http://www.sqlapi.com/ This library can do what you want.

old answer Basically you will have to iterate over the columns with sqlite3_column_name16

or sqlite3_column_name

. You will have to compare the strings they return with the one you want to find.



I used this, its MFC, but it gives you a basic idea of ​​what to do.

int CSQLite3Query::FieldIndex(const CString &field)
{
    CheckVM();

    if ( !field.IsEmpty() )
    {
        for ( int nField = 0; nField < m_nCols; nField++ )
        {
#ifdef UNICODE
            CString sTemp = (LPCTSTR)sqlite3_column_name16(m_VM, nField);
#else
            CString sTemp = (LPCTSTR)sqlite3_column_name(m_VM, nField);
#endif
            if (sTemp == field)
                return nField;
        }
    }
    else
    {
        throw new CSQLite3Exception(MFCSQLITE3_ERROR,
                                    MFCSQLITE3_INVALID_FIELD_NAME);
    }

    return -1;
}

      

+2


source


If you know the index of the column names, just create a local variable for the index of the column, for example:

int colname = 0;
int anothercol = 2; //just guessing ;-)

Results = ...
std::cout << Results[colname];
std::cout << Results[anothercol];

      

+2


source







All Articles