Solved QMYSQL insert multiple rows
-
i try to insert multiple rows in my database wich data from an array(QStrinList) so i did it like this. and it may have an error. the query excuted but the program crash after execution with this error: The program has unexpectedly finished.
//your code here void Thor::full_database() { QString namelist; QFile file("C:/Users/Wendy/Desktop/Zone_unops.txt"); if(!file.open(QFile::ReadOnly|QFile::Text)) { qDebug()<<"file couldnt not open"; } else { qDebug()<<"file opened"; QTextStream in(&file); namelist= in.readAll(); QStringList listname = namelist.split(",",QString::SkipEmptyParts); listname.sort(); file.close(); int i=1; open_data(); QSqlQuery query; while(i<=listname.size()) { query.prepare("insert into zone (Name) values(:allname)"); query.bindValue(":allname",listname[i]); if(!query.exec()) { i=listname.size()+1; // for cancelling the loop QMessageBox::critical(this,tr("error::"),query.lastError().text()); } // ending if !query.exec else { i++; }// ending else query.exec }//ending while close_data(); } // ending else if file open } // ending function full_database
-
Please update your topic, specify your title and explain your problem in the paragraph textbox, not in the title. Then wait for a reply who can help you :)
-
@Dydy02 said in i try to insert multiple rows in my database but data come from an array(QStrinList) so i did it like this. and it may have and error. the query excuted but the program crash after execution with this error: The program has unexpectedly finished.:
while(i<=listname.size())
Should be
while(i<listname.size())
Also, why do you use a while loop instead of a for loop?
-
If your database supports it, a batch insertion is probably what you want. see http://doc.qt.io/qt-5/qsqlquery.html#execBatch
P.S.
All containers in C++ start their indexes at0
and end atsize()-1
-
@jsulm thank you. i'm so nervous i know that array start at array[0] but i did it. so ridiculous. i use a while loop instead of a for loop so i can stop it in case.
it only missed -1 in the loop//your code here while(i<=listname.size()-1)
-
Hi
You should rather follow @jsulm's suggestion:
@jsulm said in QMYSQL insert multiple rows:Should be
while(i<listname.size())
It's simpler and less error prone.
-
@SGaist thank you . it is better. less code.