简体   繁体   中英

Creating common database connection for sevaral forms using qt c++

I am creating a simple qt application to provide details and login to the application and retrieve details from the database.It has mainly 2 forms(MainWindow and Dialog) A DBconncetion class has been written to obtain a database connection! I used the DBconnection class to log into application by giving details via the MainWindow form! but I don't know how to keep the connection that I opened in the MainWindow form and use it to retreive the data to the tableview in the Dialog form.

mycode is as follows

DBconnection.h (working successfully)

 public:
        QSqlDatabase mydb;
        bool connOpen(QString uname,QString pword,QString ip,int port,QString dbname){
            mydb=QSqlDatabase::addDatabase("QOCI","MyDB");
            mydb.setUserName(uname);
            mydb.setPassword(pword);
            mydb.setHostName(ip);
            mydb.setPort(port);
            mydb.setDatabaseName(dbname);
            mydb.open();
            return true;

        }

MainWindow.cpp (working successfully)

void MainWindow::on_pushButton_clicked()
    {
        DBconnection con;
        if(con.connOpen(ui->lineEdit->text(),ui->lineEdit_2->text(),ui->lineEdit_3->text(),ui->lineEdit_4->text().toInt(),ui->lineEdit_5->text())){
            Dialog dialog1;

            dialog1.setModal(true);
            dialog1.exec();

        }
   }

Dialog.cpp (not working)

void Dialog::on_pushButton_clicked()
{
    QSqlQueryModel *modal = new QSqlQueryModel();
    con.connOpen();

    QSqlQuery* qry=new QSqlQuery(con.mydb);


    qry->prepare("select NAME FROM TEST1");
       qry->exec();
       modal->setQuery(*qry);
       ui->tableView->setModel(modal);

}

How can I adjust my code so that I can retrieve data to the tablewidget in Dialog form from the connection I made from the MainWindow form?

You could either pass a reference to the connection to your dialog, or make the connection static/global.

eg1

class Dialog()
{
  DBconnection &con;
  Dialog(DBconnection &con) : con(con) {};
};

Instead of a reference, you might also want to use a std::shared_ptr .

A nice way of making the connection global/static would be through the Service locator pattern . This pattern uses a central registry known as the "service locator", which on request returns the information necessary to perform a certain task.

You might also want to have a look into things related to "Dependency injection"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM