QSqlDatabase is opened but QSqlQuery does not execute and shows error database not opened

656 views Asked by At

I am working on a project. I am trying to run this query but it fails and gives the error. Here is the code:

 QSqlQuery* printQry = new QSqlQuery();     
    if(db.Connect()){
                qDebug() << "query is done" << printQry->exec("SELECT * FROM first_weight,second_weight where fID = sID and fID ="+sr+"");
                qDebug() << printQry->lastError().text();
                db.Disconnect();
            }

Here is the error:

Database open.
QSqlQuery::exec: database not open
query is done false
"Driver not loaded Driver not loaded"
Database close.

Database open shows that database is connected and opened but the query shows the error. Can someone please explain what I am doing wrong. Thanks in advance

1

There are 1 answers

0
Yoruk On

I ran into a similar problem a couple of time ago.

You have first to open the database and assign an instance name :

   connectToDatabase()
   {
   QString connectString ;

    connectString = QString("DRIVER=SQL Server;Server=%1;Database=%2;uid=%3;pwd=%4")
        .arg(m_params.hostName)
        .arg(m_params.dataBaseName)
        .arg(m_params.userName)
        .arg(m_params.password);



         m_db = QSqlDatabase::addDatabase("QODBC","connection-name" ); 
         m_db.setHostName("localhost");



         m_db.setDatabaseName(connectString);  

         if(m_db.open())
         {
            qDebug() << "Connected to :" << m_db.hostName() ;
  
         }
         else
         {
           qDebug() << "Fail :" << m_db.lastError().text() ;
         }
          }

Note that here my instance name is "connection-name". Then, to execute a query, you have to refer to this name :

  executeQueryFirstTable()
    {
          QSqlDatabase db = QSqlDatabase::database("connection-name");
        QSqlQuery query(db); 
       QString requestForFirstTable = "INSERT INTO...";

    if(query.exec(requestForFirstTable))  
    {
        qDebug() << "Done !";
    }
}

Works fine with MS SQL Server.

Your log is saying that you have a driver problem, make sure to read this : https://doc.qt.io/qt-5/sql-driver.html