Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

No fields to update when using insertRecord



  • I'm not sure if I'm using QSqlTableModel correctly.
    I'm able to fetch data from the db but I cannot write back.

       _model = new QSqlTableModel(this, QSqlDatabase::database("myDb"));
       _model->setTable("myTable");
       _model->select();
       
       ...
    
       QSqlRecord record;
       record.setValue("sn", ui->lineSN->text()); // this is the primary key
       record.setValue("year", ui->dateProd->date().year());
       record.setValue("month", ui->dateProd->date().month());
       record.setValue("day", ui->dateProd->date().day());
       // ...set all the other fields
    
       for (int i = 0; i < record.count(); i++) record.setGenerated(i, true);
    
       int row = findRow(ui->lineSN->text()); // if the key exists -> update row
       _model->insertRecord(row, record);
       //_model->submitAll(); // not sure if I need this
       qDebug() << _model->lastError();
    

    insertRecord fails (i.e. return false) and I receive this error:

    "No Fields to update"

    This is the same even if I uncomment the commitAll line.
    What am I missing?



  • I changed my code and now it works. It's counter-intuitive and I'm not sure if it's correct - but as said it works:

    ```
    int row = findRow(ui->lineSN->text());
    
    if (row < 0)
    {
        row = _model->rowCount();
        _model->insertRow(row);
    }
    QSqlRecord record = _model->record(row);
    record.setValue("sn", ui->lineSN->text());
    record.setValue("year", ui->dateProd->date().year());
    record.setValue("month", ui->dateProd->date().month());
    record.setValue("day", ui->dateProd->date().day());
    for (int i = 0; i < record.count(); i++) record.setGenerated(i, true);
    
    _modelManufacturing->setRecord(row, record);
    _modelManufacturing->submitAll();
    


  • what are you attempting, an insert, or an update? They are DIFFERENT operations as far as the database in concerned. SQL UPDATE fails by design if it doesn't refer to an existing row. INSERT indiscriminately adds a row as long as it generates no duplicate key or referential integrity errors.


Log in to reply