Search code examples
c++sqlqt-creatorplaceholderqtsql

QT SQL Create table with placeholder as name


I want to create Tables which use the actual year as name. All I tried ended up returning an empty file.

First I tried to convert the variable to hex:

query.prepare("CREATE TABLE " + year.toUtf8().toHex() +
              "(buy_date DATE, "
               "category VARCHAR(28), "
               "price FLOAT, "
               "comment TINYTEXT)");

After I tried it with QString and arguments:

query.prepare(QString("CREATE TABLE %1 "
              "(buy_date DATE, "
               "category VARCHAR(28), "
               "price FLOAT, "
               "comment TINYTEXT)").arg(year));

And the last try was using Value binding:

query.prepare("CREATE TABLE :year "
              "(buy_date DATE, "
               "category VARCHAR(28), "
               "price FLOAT, "
               "comment TINYTEXT)");

query.bindValue(":year", year);

All failed :/


Solution

  • Well,

    It does work as it should. Can't use numbers as Table name:

    query.prepare("CREATE TABLE '" + year + "' "
                  "(buy_date DATE, "
                   "category VARCHAR(28), "
                   "price FLOAT, "
                   "comment TINYTEXT)");
    

    Or:

    query.prepare(QString("CREATE TABLE %1 "
                  "(buy_date DATE, "
                   "category VARCHAR(28), "
                   "price FLOAT, "
                   "comment TINYTEXT)").arg("'" + year + "'"));
    
    

    But I would still like to know why it doesn't work with query.bindValue?