SQLite statement CREATE TABLE with binding rowid



  • Hello guys,
    I am not a guru of SQL yet. So I come across with a problem:
    I need to execute SQL statement in context of using Qt as follows:
    CREATE TABLE IF NOT EXISTS tasks (taskId INTEGER PRIMARY KEY DEFAULT numeric_literal)
    And I need to bind numeric_literal to Value from C++ code/
    It is not clear for me how to implement this.
    Something like that:

    int taskIdFromCppCode = valueForInitialization;
    QSqlQuery query;
        query.prepare("CREATE TABLE IF NOT EXISTS tasks (taskId INTEGER PRIMARY KEY DEFAULT taskid "
                      "VALUES (:taskid)");
        query.bindValue(":taskid", taskIdFromCppCode );
        query.exec();
    

    Is that right approach or how to fill the table with my own rowids?


  • Qt Champions 2017

    @Kofr
    Hello,
    Your SQL is incorrect. Create the table and then insert the rows.

    QSqlQuery query("CREATE TABLE tasks (taskId INTEGER, PRIMARY KEY(taskId))");
    if (!query.exec())
        ; //< Handle error - table couldn't be created
    
    query.prepare("INSERT INTO tasks (taskId) VALUES (:id)");
    
    // From here on you can have multiple calls to the same piece of code to insert multiple rows
    query.bindValue(":id", valueForInitialization);
    if (!query.exec())
        ; //< Handle error - can't insert row
    

    Additionally, I advise you to create the table once and for all. Then just fill it up, instead of trying to create it on every row insertion.

    Kind regards.