SqliteModernCpp / sqlite_modern_cpp

The C++14 wrapper around sqlite library
MIT License
904 stars 156 forks source link

question about select * etc #177

Open aiafrasinei opened 5 years ago

aiafrasinei commented 5 years ago

This is more of a question, i didnt find an answer by looking at examples and tests. Im trying to convert below sqlite3 code to this c++ api.

char* sql = "SELECT * FROM multiverse;";
/*omitted some code here*/

rc = sqlite3_step(stmt);

while (rc != SQLITE_DONE && rc != SQLITE_OK) {

int colCount = sqlite3_column_count(stmt);

for (int colIndex = 0; colIndex < colCount; colIndex++) {

  int type = sqlite3_column_type(stmt, colIndex);
  const char* columnName = sqlite3_column_name(stmt, colIndex);

  if (type == SQLITE_INTEGER) {
    int valInt = sqlite3_column_int(stmt, colIndex);
    if (colIndex == 1) {
      univIndex = valInt;
    }
    if (colIndex == 3) {
      shells_nr = valInt;
    }
  }

  if (type == SQLITE_TEXT) {
    const unsigned char* valText = sqlite3_column_text(stmt, colIndex);
    if (colIndex == 2) {
      univName = std::string(reinterpret_cast<const char*>(valText));
    }
  }
}
rc = sqlite3_step(stmt);

}

rc = sqlite3_finalize(stmt);

So i translated this to sqlitemodern_cpp form:

char* sql = "SELECT idx,name,shells_nr FROM multiverse;";
*upu->getDbn() << sql
  >> [&](int idx, string name, int snr) {
  univIndex = idx;
  univName = name;
  shells_nr = snr;

  std::cout << " " << univIndex <<  " " << univName << " " << shells_nr;
};

Works great. But i dont want to change the sqls to include all the column names. Is there a way to write in sql_modern_sql to access all columns by index ?

so i can use: char sql = "SELECT FROM multiverse;";

zauguin commented 5 years ago

I wouldn't recommend this, because "SELECT * FROM multiverse;" is more fragile if the table ever changes, but sqlite_modern_cpp never parses your SQL command in any way, it is directly forwarded to sqlite. So iff your table contains three columns idx,name,shells_nr in this order, then "SELECT * FROM multiverse;" behaves in the same way as "SELECT idx,name,shells_nr FROM multiverse;";.

tl;dr: Have you tried using const char* sql = "SELECT * FROM multiverse;"; in your example code above? At least on my system, it works.