0

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?

4
  • qry.exec("CREATE TABLE xyz ....."); would be the method I have used to have c++ code dynamically create a sqlite table. Commented Jul 4, 2022 at 15:34
  • Is there a way to create database Table using models like qsqlTableModel? I am pretty sure the answer is no. QSqlTableModel is for querying an existing table not for creating or altering a tables schema. Commented Jul 4, 2022 at 15:36
  • But how should I write query if columns are not known? are you saying I should append column names to a QString and then use qry.exec(str); Commented Jul 4, 2022 at 15:42
  • are you saying I should append column names to a QString and then use qry.exec(str); Yes you can dynamically create a string in your function. Commented Jul 4, 2022 at 15:47

1 Answer 1

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.