QSqlDatabasePrivate::addDatabase: duplicate connection name 'MyConnection' error
Solved
General and Desktop
-
I have written a Qt program in c++ inorder to access a database and load database tables to table view! My program does not show any compile errors but gives 2 runtime errors
QSqlDatabasePrivate::removeDatabase: connection 'MyConnection' is still in use, all queries will cease to work. QSqlDatabasePrivate::addDatabase: duplicate connection name 'MyConnection', old connection removed.
There are mainly to classes namely MainWindow(Has database connection methods) and Dialog Following are my codes
MainWindow.h
class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); public: QSqlDatabase mydb; bool conOpen(QString userName,QString password,QString hostname,int port,QString service){ mydb=QSqlDatabase::addDatabase("QOCI","MyConnection"); mydb.setUserName(userName); mydb.setPassword(password); mydb.setHostName(hostname); mydb.setPort(port); mydb.setDatabaseName(service); return mydb.open(); }
MainWindow.cpp
void MainWindow::on_pushButton_clicked() { Dialog *dialog1 = new Dialog(this); if(conOpen(ui->uname->text(),ui->pword->text(),ui->ip->text(),ui->port->text().toInt(),ui->service->text())){ dialog1->show(); }
Dialog.h
class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); private slots: void on_pushButton_clicked();
Dialog.cpp
void Dialog::on_pushButton_clicked() { QSqlQueryModel *modal = new QSqlQueryModel(); if(QSqlDatabase::contains("MyConnection")){ QSqlQuery* qry=new QSqlQuery(QSqlDatabase::database("MyConnection")); qry->prepare("select NAME FROM Employees"); qry->exec(); modal->setQuery(*qry); ui->tableView->setModel(modal); } }
The MainWindow form is used for login and Dialog form is used to retrieve entries in database table to a table view How can I correct the issue?
Please take care to use the code tags where appropriate when making a post ~kshegunov
[Added code tags ~kshegunov]