0

I have a web domain and had already mySql database in it. I wish to connect and retrieve data from the database to my Qt Application. Here is my attempt and my result. (The host name, database name, username and password were just edited).

  QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

    db.setHostName("www.mydomain.com");
    db.setDatabaseName("myDatabase");
    db.setUserName("myName");
    db.setPassword("myPass");

    if(!db.open()){
        QSqlError err = db.lastError();
        qDebug() << err.text();
    }
    else {
        QSqlQuery qry;
        qDebug() << "Connected to SQL Database!";
        if (qry.exec("select * from dataTable;")){
            while(qry.next()){
                qDebug() << qry.value(1).toString();
            }
        }
        else {
            qDebug() << "ERROR QUERY";
        }


        qDebug() << "Closing...";
        db.close();
    }

    return a.exec();
}

It shows that it got connected but upon executing a query. It returns an error. Furthermore, I tried changing to an invalid hostname and/or username and it still got connected.

enter image description here

Maxim Makhun
  • 2,197
  • 1
  • 22
  • 26
Xegara
  • 563
  • 2
  • 10
  • 23

1 Answers1

1

1) Try w/o the semi-colon.

"For SQLite, the query string can contain only one statement at a time." (http://qt-project.org/doc/qt-4.8/qsqlquery.html#exec)

However this is one statement, the interpreter may get confused because of the semi-colon.


2) "Note that the last error for this query is reset when exec() is called." (http://qt-project.org/doc/qt-4.8/qsqlquery.html#exec)

Because this is not a prepared statement, try avoiding exec() so information about the last error is available:

QSqlQuery qry("select * from dataTable");

if(qry.lastError()) {
  // ...
}

while(qry.next()) {
  qDebug() << qry.value(1).toString();
}
marekful
  • 14,986
  • 6
  • 37
  • 59
  • 1
    Just for completeness, this would not work with bindings. Also, I am not sure what point you are trying to make with 2). It is valid (and widely used) to have a separate exec() call, and then get the text of the last error. – László Papp Jan 08 '14 at 20:11