title: QSqlDatabase and QSqlQuery in a Class (header)
body: <p>I want to create a class in my QT projecto, to handle the SQL Connection and all the necessary query's and sql transactions.</p>
  
  <p>I've found that to not have this error "QSqlQuery::exec : Database not open" I had to only initialize the QSqlQuery AFTER the QSqlDatabase has been initialized and opened.</p>
  
  <p>The problem is that I don't know how to do that... </p>
  
  <p>There is my code :</p>
  
  <pre><code>private:
     QSqlDatabase MyDBConnection;
  
     // Efectua a ligação à DB
    bool MySqlCon()
    {
        MyDBConnection = QSqlDatabase::addDatabase("QMYSQL");
        if (!MyDBConnection.isValid())
            qDebug() &lt;&lt; "ERRO DRIVER MYSQL";
  
        MyDBConnection.setHostName("localhost");
        MyDBConnection.setUserName("username");
        MyDBConnection.setPassword("password");
  
        if (MyDBConnection.open())
        {
            MySqlQuery = QSqlQuery(MyDBConnection);
            return true;
        }
        else
        {
            qDebug() &lt;&lt; MyDBConnection.lastError();
            qDebug() &lt;&lt; "Não Ligado Com Sucesso";
            return false;
        }
     }
  
  public:
      QSqlQuery MySqlQuery;
  
      // Lê valores na DB
      void DBReader(QString Query)
      {
          if(MySqlCon())
              MySqlQuery.exec(Query);
          else
              qDebug() &lt;&lt; "ERRO";
      }
  </code></pre>
  
  <p>Thanks in advance,
  Luis Da Costa</p>