Cannot insert new record when database is empty



  • I 'm working with SQLite database.
    When the database has at least one record, I can insert new record normally.
    But when it has no record, I can't insert a new record.

    The code of the new record button is this:

    void RepairDevices::on_newButton_clicked()
    {     
        isnewRecord = true;
        if (!model->isDirty()){
    	int row = mapper->currentIndex();
            mapper->submit();
            model->insertRow(row);
            mapper->setCurrentIndex(row);
    
            // clear controls
            ui.id_txt->clear();
            ui.type_cbo->clear();        
            ui.sn_txt->clear();
            ui.model_txt->clear();        
            ui.client_id_cbo->clear();
    
    	// set focus on first control
            ui.type_cbo->setFocus();
    }
    

    The code of the save button:

    void RepairDevices::on_saveButton_clicked()
    {
        model->submitAll();
        if(isnewRecord){
            mapper->toLast();
            isnewRecord = false;
            int row = mapper->currentIndex();
            updateButtons(row);
        }else{
            // do nothing
        }
    }
    

    Model is a QSqlRelationalTableModel.



  • Where is the code to insert data into db ? I suspect some logic issue in your program



  • The code that inserts data into db is this, in the save button:

        model->submitAll();
    

    Any suggestion for improving my code, is welcome.


  • Lifetime Qt Champion

    Hi,

    Your index management looks off by one. if your model is empty and you create a new row, it's index will be 0.



  • Hi SGaist.
    So, how can I fix this?



  • At last I found it!
    I had it like this:

    int row = mapper->currentIndex();
    

    Replaced with:

    int row = model->rowCount(); 
    

    and works fine!!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.