0

When i will view the data from my mysql database " mydb " , from the table "testtable", it cant open the database.

this->model = new QSqlQueryModel();
            meineView->setModel(model);

must i write it so :

 model->setQuery("SELECT id, Nachname, Vorname, Ort FROM mydb");

Or so ? :

 model->setQuery("SELECT `testtable`.`id`,`testtable`.`Nachname`,`testtable`.`Vorname`,`testtable`.`Ort`FROM `mydb`.`testtable`;");

what do i wrong ? when i delete this , my program works ( without views the data ) and when i can open it, how i put the data in my table ? ?

thelittlePanda
  • 101
  • 2
  • 10

2 Answers2

1

You need to call overriden method with your Database name. Because the database you are trying to open is not default database.

Try this :

model->setQuery("SELECT `testtable`.`id`,`testtable`.`Nachname`,`testtable`.`Vorname`,`testtable`.`Ort
`FROM `mydb`.`testtable`;","mydb");
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
0

First of all you need to connect to database using QSqlDatabase class. Then you can connect QSqlQueryModel to sql connection using proper sql query.

your first query is wrong because mydb is the database and this query needs table name:

SELECT id, Nachname, Vorname, Ort FROM testtable.

Second query is the option to choose when the query references multiple tables.

SELECT testable.id, testable.name, othertable.data FROM testable, othertable, WHERE testable.someRow = othertable.someRow

eferion
  • 872
  • 9
  • 14
  • Thank you for your fast answer. now i have this : `model->setQuery("SELECT id, Nachname, Vorname, Ort FROM testtable");` but it can't open the table. I have connect : `QSqlDatabase database = QSqlDatabase::addDatabase("QMYSQL", "conn1"); database.setHostName("127.0.0.1"); database.setPort(3306); database.setDatabaseName( "mydb" ); database.setUserName("root"); database.setPassword("testpw"); if ( !database.open() ) { qDebug("Couldn't open DB"); }` and it view the Error : QSqlQuery::exec: database not open – thelittlePanda Sep 17 '14 at 11:49
  • If `database` is not a pointer you must be sure this object is alive when you call querys. `QSqlDatabase` destructor closes and releases the connection. – eferion Sep 17 '14 at 12:36
  • Okey, but when i put `QSqlDatabase database = QSqlDatabase::addDatabase("QMYSQL", "conn1");` with the connections like sethost etc. in my pushbuttonclicked() method, it doen't worked to . – thelittlePanda Sep 17 '14 at 13:01
  • `QSqlDatabase database = QSqlDatabase::addDatabase("QMYSQL", "conn1");` this code creates database object in stack, when code leaves current method, this instance is automatically destroyed and conection is closed. Try to create database connection as member of current dialog. – eferion Sep 17 '14 at 13:30