Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QSqlQueryModel and QSqlDatabase::removeDatabase empty data in tableview

QSqlQueryModel and QSqlDatabase::removeDatabase empty data in tableview

Scheduled Pinned Locked Moved Unsolved General and Desktop
10 Posts 2 Posters 417 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    kipalex
    wrote on last edited by
    #1

    Good afternoon!

    I can't understand how to properly use the model to close and delete a connection to the database.

    If I delete the QSqlDatabase:: removeDatabase connection, then my table is empty when queried. If I do not delete, a warning appears when the request is repeated (QSqlDatabasePrivate:: addDatabase: duplicate connection name 'SearchByDate', old connection removed.).

    // Поиск звонков за выбранный период
    void MainWindow::GetSearchByDate()
    {
        // Добавляем строку запроса к календарю (переменная)
        QString valueToSearch = ui->lineEditByDate->text();
    
        // Дату надо переформатировать в формат ToString("yyyy-MM-dd")
        QString Date1 = ui->dateEdit1->date().toString("yyyy-MM-dd");
        QString Date2 = ui->dateEdit2->date().toString("yyyy-MM-dd");
        {
        QSqlDatabase db = QSqlDatabase::addDatabase( "QMYSQL", "SearchByDate");
    
        db.setHostName( "IP" );
        db.setDatabaseName( "db_name" );
        db.setUserName( "db_user" );
        db.setPassword( "db_pass");
    
        if( bool ok = db.open() )
        {
            {
            // Вводные данные
            // Запрос для общей таблицы за конкретный день
            QSqlQueryModel *SearchByDate = new QSqlQueryModel();
            SearchByDate->setQuery( "SELECT calldate, src, realdst, billsec, disposition, uniqueid FROM cdr WHERE realdst LIKE '%" + valueToSearch + "%' AND calldate BETWEEN '" + Date1 + "' AND '" + Date2 + "' OR src LIKE '%" + valueToSearch + "%' AND calldate BETWEEN '" + Date1 + "' AND '" + Date2 + "' ", db);
    
                for (int i = 0; i < SearchByDate->rowCount(); i++)
                {
                    ui->tableView1->setModel(SearchByDate);
                    // Сортировка через QSortFilterProxyModel
                    QSortFilterProxyModel *proxyCurrentDayFull = new QSortFilterProxyModel();
                    proxyCurrentDayFull->setSourceModel(SearchByDate);
                    ui->tableView1->setModel(proxyCurrentDayFull);
                    SearchByDate->setHeaderData( 0, Qt::Horizontal, QObject::tr("Дата звонка") ); // задаем название первого столбца
                    SearchByDate->setHeaderData( 1, Qt::Horizontal, QObject::tr("Исходящий номер") ); // задаем название второго столбца
                    SearchByDate->setHeaderData( 2, Qt::Horizontal, QObject::tr("Набранный номер") ); // задаем название третьего столбца
                    SearchByDate->setHeaderData( 3, Qt::Horizontal, QObject::tr("Продолжительность вызова") ); // задаем название пятого столбца
                    SearchByDate->setHeaderData( 4, Qt::Horizontal, QObject::tr("Статус звонка") ); // задаем название шестого столбца
                    SearchByDate->setHeaderData( 5, Qt::Horizontal, QObject::tr("Уникальный номер") ); // задаем название седьмого столбца
                    ui->tableView1->show();
    
                }
            }
        }
    
        else
        {
            QMessageBox::critical(this,"Ошибка подключения к БД", db.lastError().text(), QMessageBox::Ok);
        }
        db.close();
        }
        //QSqlDatabase::removeDatabase("SearchByDate"); // Удаляем наше соединение
    }
    
    Christian EhrlicherC 1 Reply Last reply
    0
    • K kipalex

      Good afternoon!

      I can't understand how to properly use the model to close and delete a connection to the database.

      If I delete the QSqlDatabase:: removeDatabase connection, then my table is empty when queried. If I do not delete, a warning appears when the request is repeated (QSqlDatabasePrivate:: addDatabase: duplicate connection name 'SearchByDate', old connection removed.).

      // Поиск звонков за выбранный период
      void MainWindow::GetSearchByDate()
      {
          // Добавляем строку запроса к календарю (переменная)
          QString valueToSearch = ui->lineEditByDate->text();
      
          // Дату надо переформатировать в формат ToString("yyyy-MM-dd")
          QString Date1 = ui->dateEdit1->date().toString("yyyy-MM-dd");
          QString Date2 = ui->dateEdit2->date().toString("yyyy-MM-dd");
          {
          QSqlDatabase db = QSqlDatabase::addDatabase( "QMYSQL", "SearchByDate");
      
          db.setHostName( "IP" );
          db.setDatabaseName( "db_name" );
          db.setUserName( "db_user" );
          db.setPassword( "db_pass");
      
          if( bool ok = db.open() )
          {
              {
              // Вводные данные
              // Запрос для общей таблицы за конкретный день
              QSqlQueryModel *SearchByDate = new QSqlQueryModel();
              SearchByDate->setQuery( "SELECT calldate, src, realdst, billsec, disposition, uniqueid FROM cdr WHERE realdst LIKE '%" + valueToSearch + "%' AND calldate BETWEEN '" + Date1 + "' AND '" + Date2 + "' OR src LIKE '%" + valueToSearch + "%' AND calldate BETWEEN '" + Date1 + "' AND '" + Date2 + "' ", db);
      
                  for (int i = 0; i < SearchByDate->rowCount(); i++)
                  {
                      ui->tableView1->setModel(SearchByDate);
                      // Сортировка через QSortFilterProxyModel
                      QSortFilterProxyModel *proxyCurrentDayFull = new QSortFilterProxyModel();
                      proxyCurrentDayFull->setSourceModel(SearchByDate);
                      ui->tableView1->setModel(proxyCurrentDayFull);
                      SearchByDate->setHeaderData( 0, Qt::Horizontal, QObject::tr("Дата звонка") ); // задаем название первого столбца
                      SearchByDate->setHeaderData( 1, Qt::Horizontal, QObject::tr("Исходящий номер") ); // задаем название второго столбца
                      SearchByDate->setHeaderData( 2, Qt::Horizontal, QObject::tr("Набранный номер") ); // задаем название третьего столбца
                      SearchByDate->setHeaderData( 3, Qt::Horizontal, QObject::tr("Продолжительность вызова") ); // задаем название пятого столбца
                      SearchByDate->setHeaderData( 4, Qt::Horizontal, QObject::tr("Статус звонка") ); // задаем название шестого столбца
                      SearchByDate->setHeaderData( 5, Qt::Horizontal, QObject::tr("Уникальный номер") ); // задаем название седьмого столбца
                      ui->tableView1->show();
      
                  }
              }
          }
      
          else
          {
              QMessageBox::critical(this,"Ошибка подключения к БД", db.lastError().text(), QMessageBox::Ok);
          }
          db.close();
          }
          //QSqlDatabase::removeDatabase("SearchByDate"); // Удаляем наше соединение
      }
      
      Christian EhrlicherC Offline
      Christian EhrlicherC Offline
      Christian Ehrlicher
      Lifetime Qt Champion
      wrote on last edited by
      #2

      @kipalex open the database once and not on every call. Currently you create a new connection every time and since you give them a name the default name is used. Since a database connection needs a unique name you get the warning.

      Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
      Visit the Qt Academy at https://academy.qt.io/catalog

      K 1 Reply Last reply
      1
      • Christian EhrlicherC Christian Ehrlicher

        @kipalex open the database once and not on every call. Currently you create a new connection every time and since you give them a name the default name is used. Since a database connection needs a unique name you get the warning.

        K Offline
        K Offline
        kipalex
        wrote on last edited by
        #3

        @Christian-Ehrlicher said in QSqlQueryModel and QSqlDatabase::removeDatabase empty data in tableview:

        open the database once and not on every call. Currently you create a new connection every time and since you give them a name the default name is used. Since a database connection needs a unique name you get the warning.

        Yes, everything is correct, but I set the connection name. and the connection takes place by that name. But if after completing the connection, I close and delete the data empty. If you do not delete, then there is data.

        Christian EhrlicherC 1 Reply Last reply
        0
        • K kipalex

          @Christian-Ehrlicher said in QSqlQueryModel and QSqlDatabase::removeDatabase empty data in tableview:

          open the database once and not on every call. Currently you create a new connection every time and since you give them a name the default name is used. Since a database connection needs a unique name you get the warning.

          Yes, everything is correct, but I set the connection name. and the connection takes place by that name. But if after completing the connection, I close and delete the data empty. If you do not delete, then there is data.

          Christian EhrlicherC Offline
          Christian EhrlicherC Offline
          Christian Ehrlicher
          Lifetime Qt Champion
          wrote on last edited by
          #4

          @kipalex That's the correct behavior. A QSqlQueryModel needs an open db connection so it can receive the data from the db when it's needed.

          Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
          Visit the Qt Academy at https://academy.qt.io/catalog

          K 1 Reply Last reply
          0
          • Christian EhrlicherC Christian Ehrlicher

            @kipalex That's the correct behavior. A QSqlQueryModel needs an open db connection so it can receive the data from the db when it's needed.

            K Offline
            K Offline
            kipalex
            wrote on last edited by
            #5

            @Christian-Ehrlicher Wait, then it turns out that the correct solution will not delete the existing connection, but check if the connection is to use it.

            Christian EhrlicherC 1 Reply Last reply
            0
            • K kipalex

              @Christian-Ehrlicher Wait, then it turns out that the correct solution will not delete the existing connection, but check if the connection is to use it.

              Christian EhrlicherC Offline
              Christian EhrlicherC Offline
              Christian Ehrlicher
              Lifetime Qt Champion
              wrote on last edited by
              #6

              @kipalex That's what I said in my first post...

              Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
              Visit the Qt Academy at https://academy.qt.io/catalog

              K 1 Reply Last reply
              0
              • Christian EhrlicherC Christian Ehrlicher

                @kipalex That's what I said in my first post...

                K Offline
                K Offline
                kipalex
                wrote on last edited by
                #7

                @Christian-Ehrlicher Good. I tried to execute the request through a connection check and still get a warning.

                QSqlDatabase db = QSqlDatabase::addDatabase( "QMYSQL", **"SearchByDate"**);
                
                    db.setHostName( "db_host" );
                    db.setDatabaseName( "db_name" );
                    db.setUserName( "db_user" );
                    db.setPassword( "db_pass");
                
                    **if( QSqlDatabase::contains( "SearchByDate" ) )**
                    {
                        QSqlDatabase db = QSqlDatabase::database( **"SearchByDate"** );
                        // Вводные данные
                        // Запрос для общей таблицы за конкретный день
                        QSqlQueryModel *SearchByDate = new QSqlQueryModel();
                        SearchByDate->setQuery( "SELECT calldate, src, realdst, billsec, disposition, uniqueid FROM cdr WHERE realdst LIKE '%" + valueToSearch + "%' AND calldate BETWEEN '" + Date1 + "' AND '" + Date2 + "' OR src LIKE '%" + valueToSearch + "%' AND calldate BETWEEN '" + Date1 + "' AND '" + Date2 + "' ", db);
                        SearchByDate->setHeaderData( 0, Qt::Horizontal, QObject::tr("Дата звонка") ); // задаем название первого столбца
                        SearchByDate->setHeaderData( 1, Qt::Horizontal, QObject::tr("Исходящий номер") ); // задаем название второго столбца
                        SearchByDate->setHeaderData( 2, Qt::Horizontal, QObject::tr("Набранный номер") ); // задаем название третьего столбца
                        SearchByDate->setHeaderData( 3, Qt::Horizontal, QObject::tr("Продолжительность вызова") ); // задаем название пятого столбца
                        SearchByDate->setHeaderData( 4, Qt::Horizontal, QObject::tr("Статус звонка") ); // задаем название шестого столбца
                        SearchByDate->setHeaderData( 5, Qt::Horizontal, QObject::tr("Уникальный номер") ); // задаем название седьмого столбца
                        // Сортировка через QSortFilterProxyModel
                        QSortFilterProxyModel *proxyCurrentDayFull = new QSortFilterProxyModel();
                        proxyCurrentDayFull->setSourceModel(SearchByDate);
                        ui->tableView1->setModel(proxyCurrentDayFull);
                        ui->tableView1->show();
                        db.close();
                    }
                    else
                    {
                        QMessageBox::critical(this,"Ошибка подключения к БД", db.lastError().text(), QMessageBox::Ok);
                    }
                
                Christian EhrlicherC 1 Reply Last reply
                0
                • K kipalex

                  @Christian-Ehrlicher Good. I tried to execute the request through a connection check and still get a warning.

                  QSqlDatabase db = QSqlDatabase::addDatabase( "QMYSQL", **"SearchByDate"**);
                  
                      db.setHostName( "db_host" );
                      db.setDatabaseName( "db_name" );
                      db.setUserName( "db_user" );
                      db.setPassword( "db_pass");
                  
                      **if( QSqlDatabase::contains( "SearchByDate" ) )**
                      {
                          QSqlDatabase db = QSqlDatabase::database( **"SearchByDate"** );
                          // Вводные данные
                          // Запрос для общей таблицы за конкретный день
                          QSqlQueryModel *SearchByDate = new QSqlQueryModel();
                          SearchByDate->setQuery( "SELECT calldate, src, realdst, billsec, disposition, uniqueid FROM cdr WHERE realdst LIKE '%" + valueToSearch + "%' AND calldate BETWEEN '" + Date1 + "' AND '" + Date2 + "' OR src LIKE '%" + valueToSearch + "%' AND calldate BETWEEN '" + Date1 + "' AND '" + Date2 + "' ", db);
                          SearchByDate->setHeaderData( 0, Qt::Horizontal, QObject::tr("Дата звонка") ); // задаем название первого столбца
                          SearchByDate->setHeaderData( 1, Qt::Horizontal, QObject::tr("Исходящий номер") ); // задаем название второго столбца
                          SearchByDate->setHeaderData( 2, Qt::Horizontal, QObject::tr("Набранный номер") ); // задаем название третьего столбца
                          SearchByDate->setHeaderData( 3, Qt::Horizontal, QObject::tr("Продолжительность вызова") ); // задаем название пятого столбца
                          SearchByDate->setHeaderData( 4, Qt::Horizontal, QObject::tr("Статус звонка") ); // задаем название шестого столбца
                          SearchByDate->setHeaderData( 5, Qt::Horizontal, QObject::tr("Уникальный номер") ); // задаем название седьмого столбца
                          // Сортировка через QSortFilterProxyModel
                          QSortFilterProxyModel *proxyCurrentDayFull = new QSortFilterProxyModel();
                          proxyCurrentDayFull->setSourceModel(SearchByDate);
                          ui->tableView1->setModel(proxyCurrentDayFull);
                          ui->tableView1->show();
                          db.close();
                      }
                      else
                      {
                          QMessageBox::critical(this,"Ошибка подключения к БД", db.lastError().text(), QMessageBox::Ok);
                      }
                  
                  Christian EhrlicherC Offline
                  Christian EhrlicherC Offline
                  Christian Ehrlicher
                  Lifetime Qt Champion
                  wrote on last edited by
                  #8

                  @kipalex Did you ever read my posts? Open the db once in an init function, don't close it as long as the model is alive

                  Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                  Visit the Qt Academy at https://academy.qt.io/catalog

                  K 1 Reply Last reply
                  0
                  • Christian EhrlicherC Christian Ehrlicher

                    @kipalex Did you ever read my posts? Open the db once in an init function, don't close it as long as the model is alive

                    K Offline
                    K Offline
                    kipalex
                    wrote on last edited by
                    #9

                    @Christian-Ehrlicher Thank you very much!

                    I put the connection itself in the initialization of the program. And from there I already take it. The warning is gone.

                    I ask for petitions again, I just have been dealing with QT for a long time.

                    Christian EhrlicherC 1 Reply Last reply
                    0
                    • K kipalex

                      @Christian-Ehrlicher Thank you very much!

                      I put the connection itself in the initialization of the program. And from there I already take it. The warning is gone.

                      I ask for petitions again, I just have been dealing with QT for a long time.

                      Christian EhrlicherC Offline
                      Christian EhrlicherC Offline
                      Christian Ehrlicher
                      Lifetime Qt Champion
                      wrote on last edited by
                      #10

                      That is the way to go. Also don't use a QSqlDatabase object as member. Always reference it through the static functions and it's name.

                      Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                      Visit the Qt Academy at https://academy.qt.io/catalog

                      1 Reply Last reply
                      1

                      • Login

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • Users
                      • Groups
                      • Search
                      • Get Qt Extensions
                      • Unsolved