Please nominate your Qt Champions for 2021! https://forum.qt.io/topic/132134/looking-for-the-2021-qt-champions

QSqlQuery adds records twice



  • Hi,
    I have the following code:

     db = QSqlDatabase::addDatabase ("QSQLITE","submit");
       db.setDatabaseName (fileQstring );
       db.open ();
       QSqlQuery querys(db);
    
       if(!db.open ())
       {
           qDebug() << "The database is not open (submit)!";
       }
       else
       {
           qDebug() << "The database is open (submit)!";
       }
    
    	QFile file(fileName);
    
        if(file.open (QIODevice::ReadOnly))
        {
            qDebug() << "File " << fileName << " is open!";
            byteArray = file.readAll ();
        }
        else
        {
            qDebug() << "File " << fileName << " is NOT open!";
        }
    
        qDebug() << "Original data " <<byteArray.size() << "bytes.";
    
        qDebug() <<"Byte size: " << byteArray.size();
    
       querys.prepare("INSERT INTO Items (ID, Name, Pic, Description, Month, Day, Year, History, Age, Notes, Color, Material, Signed, What)" "VALUES(:ID, :Name, :Pic, :Description, :Month, :Day, :Year, :History, :Age, :Notes, :Color, :Material, :Signed, :What)" );
       querys.bindValue (":ID",sID);
       querys.bindValue (":Name",name);
       querys.bindValue (":Pic",byteArray);
       querys.bindValue (":Description",description);
       querys.bindValue (":Month",month);
       querys.bindValue (":Day",day);
       querys.bindValue (":Year",year);
       querys.bindValue (":History",history);
       querys.bindValue (":Age",age);
       querys.bindValue (":Notes",notes);
       querys.bindValue (":Color",newColor);
       querys.bindValue (":Material",newMaterial);
       querys.bindValue (":Signed",newSignedby);
       querys.bindValue (":What",newWhat);
    
       querys.exec ();
    
       if(!querys.exec())
       {
           qDebug() <<"Error inserting into the main db!" << querys.lastError ();
    
       }
    

    It works fine, but please help me to figure out why it inserts each record twice.
    Thank you.


  • Lifetime Qt Champion

    @gabor53 said:

    querys.exec (); << first time

    if(!querys.exec()) << next time
    {

    Hi, you exceute it twice :)

    bool result = querys.exec ();
    if(!result)
    {



  • @mrjj
    I changed the last few lines like this:

       bool result = querys.exec ();
    
       if(!result)
       {
           qDebug() <<"Error inserting into the main db!" << querys.lastError ();
    
       }
    

    Now it adds a blank line, all fields with NULL in them. What did I mess up?
    Thanks.


  • Lifetime Qt Champion

    dont know. should work as before. just not inserting twice.


Log in to reply