0

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\".

m.taheri
  • 309
  • 3
  • 21
  • is there a table named precisely 'mytable' in your 'mydb' database ? If so, can you query successfully it from another SQL client? – Edd Mar 17 '17 at 15:59
  • @Edd, yes I have it. I can read query it by QSQLQuery without any problem. – m.taheri Mar 17 '17 at 16:03

2 Answers2

4

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");
m.taheri
  • 309
  • 3
  • 21
0

According to http://doc.qt.io/qt-5/qsqltablemodel.html#QSqlTableModel the constructor of QSqlTablemodel:

Creates an empty QSqlTableModel and sets the parent to parent and the database connection to db. If db is not valid, the default database connection will be used.

In the event that your db object is not valid you would connect to a default database where your table is not available.

Double check the parameters used to initialize and setup QSqlDatabase db.

Edd
  • 1,350
  • 11
  • 14
  • As I said the database connection is ok since isValid() and open() methods of my QSQLDatabase object return true. I can query database by QSQLQuery. – m.taheri Mar 17 '17 at 16:17
  • Mh, if you say that the **same** db object works fine with QSQLQuery then I am not too sure. Maybe try updating your answer with the CREATE statement used to create the table, so people may have some extra info to tackle this – Edd Mar 17 '17 at 16:24