Works fine here with Sqlite but not MySql... it is going to be a MySQL quirk.
Here is my take:
#include <QtCore>
#include <QtSql>
#include <QDebug>
int main(int argc, char *argv[])
{
db.setDatabaseName("testdb");
db.setUserName("user");
db.setPassword("password");
if (db.open()) {
// Create a test table
db.exec("CREATE TABLE zzz_test (a int, b varchar(10))");
db.exec("INSERT INTO zzz_test VALUES (1, 'Apple')");
db.exec("INSERT INTO zzz_test VALUES (2, 'Banana')");
db.exec("INSERT INTO zzz_test VALUES (3, 'Cherry')");
QSqlQuery q2
(db
);
// Fails badly if declared here if (q1.exec("SELECT * from zzz_test")) {
while(q1.next()) {
// QSqlQuery q2(db); // fails less badly here because it is destroyed at the end of the loop
qDebug() << "Before q2" << q1.record() << q1.lastError().text();
// Any failing query
if (!q2.exec("select * from zzz_nonexistent"))
qDebug() << "q2 failed" << q2.lastError().text();
// q2.clear(); // Adding this fixes the next line
qDebug() << "After q2" << q1.record() << q1.lastError().text();
}
}
db.exec("DROP TABLE zzz_test");
}
return 0;
}
#include <QtCore>
#include <QtSql>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setDatabaseName("testdb");
db.setUserName("user");
db.setPassword("password");
if (db.open()) {
// Create a test table
db.exec("CREATE TABLE zzz_test (a int, b varchar(10))");
db.exec("INSERT INTO zzz_test VALUES (1, 'Apple')");
db.exec("INSERT INTO zzz_test VALUES (2, 'Banana')");
db.exec("INSERT INTO zzz_test VALUES (3, 'Cherry')");
QSqlQuery q1(db);
QSqlQuery q2(db); // Fails badly if declared here
if (q1.exec("SELECT * from zzz_test")) {
while(q1.next()) {
// QSqlQuery q2(db); // fails less badly here because it is destroyed at the end of the loop
qDebug() << "Before q2" << q1.record() << q1.lastError().text();
// Any failing query
if (!q2.exec("select * from zzz_nonexistent"))
qDebug() << "q2 failed" << q2.lastError().text();
// q2.clear(); // Adding this fixes the next line
qDebug() << "After q2" << q1.record() << q1.lastError().text();
}
}
db.exec("DROP TABLE zzz_test");
}
return 0;
}
To copy to clipboard, switch view to plain text mode
I'd be inclined to raise a bug.
Bookmarks