I need to populate a QTableView by retrieving data from a QSqlTableModel object. I use following commands to make a connection to a sql server database:
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
QString connectionTemplate = "DRIVER={SQL Native Client};SERVER=%1;DATABASE=%2;Uid=username;Pwd=password;Trusted_Connection=Yes;";
QString connectionString = connectionTemplate.arg("localhost").arg("mydb");
db.setDatabaseName(connectionString);
I validate the database connection by the methods isValid() and open() from QSqlDatabase class. I am also able to query from the database tables properly. ٍEvery thing is ok so far. But the problem arises when I use following commands:
QSqlTableModel* model = new QSqlTableModel(parent,db);
model->setTable("mytable");
qDebug() << model->lastError().text(); // the error message is printed on consul.
The method setTable not working and causes an error: Unable to find table \"mytable\".
I found the solution. I should open the database right after setDatabaseName and before creation of QSqlTableModel:
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
QString connectionTemplate = "DRIVER={SQL Native Client};SERVER=%1;DATABASE=%2;Uid=username;Pwd=password;Trusted_Connection=Yes;";
QString connectionString = connectionTemplate.arg("localhost").arg("mydb");
db.setDatabaseName(connectionString);
db.open(); // :)
QSqlTableModel* model = new QSqlTableModel(parent,db);
model->setTable("mytable");