views:

541

answers:

3

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

For example, Python's SQLite access allows dictionary access

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

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

+2  A: 

newer answer http://www.sqlapi.com/ This library might do what you want it to.

old answer Basically you will have to iterate the columns with sqlite3_column_name16 or sqlite3_column_name. You will have to compare the strings these return with the one you want to look up.

I have used this, its MFC, but it gives you the basic idea of what needs done.

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;
}
Daniel A. White
+2  A: 

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

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

Results = ...
std::cout << Results[colname];
std::cout << Results[anothercol];
lothar
Not very elegant...
Daniel A. White
But very efficient if you don't need dynamic column names :-)
lothar
+2  A: 

I'd go with Daniel in recommending SQLAPI++ 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 bit verbose so here's a code-only gist:

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);
  }
}
Alex Martelli