How to create a database table if the fields are declared at run time?

173 Views Asked by At

When creating table at run time using qsqlquery the fields of the sqlite database table are declared by user, and using that I want to create a table at run time. How can I do that in qsql cpp?

qsqlQuery qry;
qry.exec("CREATE TABLE xyz ....."); // ???

Is there a way to create database Table using models like qsqlTableModel?

1

There are 1 best solutions below

0
Alexander Dyagilev On BEST ANSWER

A code from my project. Just copied and pasted as is, but I think it should be enough for you to understand how to achieve your goal.

bool SqlTableManager::createTable()
{   
    QString qs = "CREATE TABLE IF NOT EXISTS ";
    qs += m_tableName + " (";

    bool firstElem = true;

    QString primaryKeys;

    for (auto &&item : m_columns)
    {
        if (!firstElem)
            qs += ", ";
        firstElem = false;
        qs += item.name + " " + item.type;
        if (item.primary)
        {
            if (!primaryKeys.isEmpty())
                primaryKeys += ", ";
            primaryKeys += item.name;
        }
    }

    if (!primaryKeys.isEmpty())
    {
        qs += ", PRIMARY KEY (";
        qs += primaryKeys;
        qs += ")";
    }

    qs += ")";
   
    auto [q,r] = m_db->createQuery(qs);
    if (!r || !q.exec())
    {
        setLastError(q.lastError());
        return false;
    }
    else
    {
        clearLastError();
        return true;
    }
}