qtqsqlqueryqsqltablemodelqsqldatabase

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


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?


Solution

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