2015-04-25 37 views
0

我試圖做一個消息顯示一次,如果一個循環中的查詢成功執行。 當我這樣做;如何使消息顯示一次使用QMessage

QSqlQuery query1; 
for (int i = 0; i < itemEdits.size(); i++) { 
    query1.prepare("INSERT INTO class1_bills (bill_item, amount) VALUES (:bill_item, :amount)"); 
    query1.bindValue(":bill_item", ""+itemEdits[i]->text()+""); 
    query1.bindValue(":amount", ""+amountEdits[i]->text()+""); 
} 
if (query1.exec()) { 
    close(); 
    QMessageBox::warning(0, "success", "Bill for Class 1 successfully prepared"); 

} 
else { 
    close(); 
    QMessageBox::warning(0, "failed", "Bill for Class 1 could not be prepared"); 

} 

查詢在表中只插入1條記錄。即如果它應該通過循環插入表3中的記錄,它只做一次。 如果這樣做;

QSqlQuery query1; 
for (int i = 0; i < itemEdits.size(); i++) { 
    query1.prepare("INSERT INTO class1_bills (bill_item, amount) VALUES (:bill_item, :amount)"); 
    query1.bindValue(":bill_item", ""+itemEdits[i]->text()+""); 
    query1.bindValue(":amount", ""+amountEdits[i]->text()+""); 

    if (query1.exec()) { 
     close(); 
     QMessageBox::warning(0, "success", "Bill for Class 1 successfully prepared"); 

    } 
    else { 
     close(); 
     QMessageBox::warning(0, "failed", "Bill for Class 1 could not be prepared"); 

    } 
} 

該消息顯示等效於循環的次數。但是我希望消息只顯示一次,無論循環執行的次數如何。我該怎麼做?

回答

1

在第一個代碼中,當它應該在循環中時,您將在循環 之外執行查詢,以便插入所有循環記錄數。這使查詢只執行一次。

在第二個代碼中,您通過在循環中執行查詢來做正確的事情 因此它插入了循環的所有記錄數。但是,您在消息循環中應該顯示'曾經' ,這使得消息在每次循環插入表中時都會顯示消息。 爲了解決這個問題,將執行分配給已經聲明的循環中的Boolean變量(可能已初始化,因爲編譯器可能會發出警告it maybe used uninitialized)已經在循環 之外,並在if這樣的語句中使用它;

QSqlQuery query1; 
//declared and initialized here 
bool ok = 0; 
for (int i = 0; i < itemEdits.size(); i++) { 
    query1.prepare("INSERT INTO class1_bills (bill_item, amount) VALUES (:bill_item, :amount)"); 
    query1.bindValue(":bill_item", ""+itemEdits[i]->text()+""); 
    query1.bindValue(":amount", ""+amountEdits[i]->text()+""); 

    //assigned here 
    ok = query1.exec(); 
} 
//used here 
if (ok) { 
    close(); 
    QMessageBox::warning(0, "success", "Bill for Class 1 successfully prepared"); 

} 
else { 
    close(); 
    QMessageBox::warning(0, "failed", "Bill for Class 1 could not be prepared"); 

} 

這應該可以解決您的問題。

+0

感謝您的解釋。 –

相關問題