【问题标题】:SQLite C++ Access Columns by NameSQLite C++ 按名称访问列
【发布时间】:2009-05-03 22:13:54
【问题描述】:

有没有办法通过列名(如 C++ 映射)而不是 C/C++ 中的索引号来访问 SQLite 结果?

例如 Python 的 SQLite 访问允许字典访问

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

在 C++ 中是否有任何类似的方法可用于 SQLite 的接口?

【问题讨论】:

    标签: c++ c sqlite dictionary map


    【解决方案1】:

    我会和 Daniel 一起在 www.sqlapi.com 上推荐 SQLAPI++——在http://www.sqlapi.com/HowTo/fetch.html,您可以找到一个按名称获取字段的简单示例。这个例子有点冗长,所以这里是一个纯代码要点:

    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】:

      如果您知道列名的索引,只需为列索引创建一个局部变量,例如:

      int colname = 0;
      int anothercol = 2; //just guessing ;-)
      
      Results = ...
      std::cout << Results[colname];
      std::cout << Results[anothercol];
      

      【讨论】:

      • 但如果您不需要动态列名,则非常有效:-)
      【解决方案3】:

      较新的答案 http://www.sqlapi.com/ 这个库可以做你想做的事。

      旧答案 基本上,您必须使用sqlite3_column_name16sqlite3_column_name 迭代列。您必须将这些返回的字符串与您要查找的字符串进行比较。

      我使用过它,它的 MFC,但它可以让您了解需要做什么。

      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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-27
        • 2013-02-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多