behruz montazeri
behruz montazeri

Reputation: 116

connection 'qt_sql_default_connection' is still in use, all queries will cease to work

I've made separate functions for open and close connection.But it wont let me to add new record on new form. this is login header file.

public:
QSqlDatabase mydb;
void connClose()
{

    //QString connection;
    //connection = mydb.connectionName();
    mydb.close();
    //mydb.removeDatabase(connection);
    mydb.removeDatabase(mydb.connectionName());
}
bool connOpen()
{
    mydb=QSqlDatabase::addDatabase("QSQLITE");
    mydb.setDatabaseName("./Poem.db");
    if(mydb.open())
    {
        return true;
    }
    else if(!mydb.open())
    {
        return false;
    }

}

this is the other form add button :

QString Title,Group,Poem;

Title = ui->lineEdit->text();
Group = ui->label_2->text();
Poem = ui->textEdit->toPlainText();



MainWindow mainwindow;
mainwindow.connOpen();



 QSqlQuery * qry1 = new QSqlQuery(mainwindow.mydb);

 qry1->prepare("insert into Poems(Title,Poem,Group) values ('"+Title+"','"+Poem+"','"+Group+"')");

 if(qry1->exec())
 {
     QMessageBox::critical(this,tr("درج شعر جدید"),tr("شعر اضافه شد"));
     mainwindow.connClose();
 }

I get this errors :

duplicate connection name 'qt_sql_default_connection', old connection removed. connection 'qt_sql_default_connection' is still in use, all queries will cease to work.

Upvotes: 2

Views: 4651

Answers (1)

Mohammad Kanan
Mohammad Kanan

Reputation: 4582

You are committing exactly what Qt QSqlDatabase Documentation warns about:

Warning: There should be no open queries on the database connection when this function is called

...

// WRONG

QSqlDatabase db = QSqlDatabase::database("sales");
QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
QSqlDatabase::removeDatabase("sales"); // will output a warning

// "db" is now a dangling invalid database connection, // "query" contains an invalid result set

and the correct is:

{
    QSqlDatabase db = QSqlDatabase::database("sales");
    QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
}

// Both "db" and "query" are destroyed because they are out of scope

  QSqlDatabase::removeDatabase("sales"); // correct

So in your case you execute query qry1 and remove the database within same scope (i.e before qry1 goes out of scope), you should modify your code to make sure qry1 is executed and gets destroyed / goes out of scope / before deleting the database. Try this:

{
 QSqlQuery * qry1 = new QSqlQuery(mainwindow.mydb);
 qry1->prepare("insert into Poems(Title,Poem,Group) values ('"+Title+"','"+Poem+"','"+Group+"')");
 if(qry1->exec())
 {
     QMessageBox::critical(this,tr("درج شعر جدید"),tr("شعر اضافه شد"));
 }
}
     mainwindow.connClose();

Upvotes: 3

Related Questions