ComboBox read info from database table and close connection in different ui. than opened



  • Hi,
    I would like to draw your attention to the following scenario:
    I created a connection to insert some info into my database table1 (driver QMYSQL). I have an ui. form to create users account; info to be feed in my database table1: username, name, pass, etc. and role assign to specific user. For “role” I would like to have a comboBox which receive info from my database table2. Are only 3 roles available: admin, guest, user.
    I have several questions which came in my mind:

    1. how to populate the comboBox with these roles read from table2?

    2. The connection opens the database when the ui. form opens.
      @void MainWindow::on_addUser_triggered()
      {
      usernew *nU = new usernew;
      nU ->show();

      QSqlDatabase addUser = QSqlDatabase::addDatabase("QMYSQL");
      addUser.setConnectOptions();
      addUser.setDatabaseName("test");
      addUser.setUserName("admin");
      addUser.setPassword("pass");
      addUser.open();@

    a. I was thinking to lunch a query as soon as the ui. form is opened and to populate the comboBox with the results from table2:
    @QSqlQuery combRol;
    combRol.prepare("SELECT role FROM test.table2");
    combRol->setHeaderData(1, Qt::Horizontal, tr("Role"));
    QTableView *view = new QTableView;
    ui->Role->setModel(combRol);
    ui->Role->setView(view);@

    b. But this solution is not working. Any idea what I’m doing wrong? Or do you have other alternative?

    1. After the info was inserted in all fields I need to INSERT the info via a query in my table1 and close the connection:
      @void usernew::on_buttonBox_accepted()
      {
      QSqlQuery qry1;
      qry1.prepare("INSERT INTO test.table1 (username, pass, name, email)VALUES (:username, :pass, :name, :email)");
      qry1.bindValue(":username", ui->Username->text());
      qry1.bindValue(":pass", ui->Password->text());
      qry1.bindValue(":name", ui->Name->text());
      qry1.bindValue(":email", ui->Email->text());
      qry1.exec();
      addUser.close();
      }@
      a. But the addUser.close is not working since the connection is declared/opened in a different form “MainWindow” and now I would like to close it in “usernew”. Any idea what is wrong and what shall I do to close the connection in “usernew”?

    2. Is it correct (from architecture point of view) to open a connection in one form and close it in a different one?
      Thanks for your hints.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.