0

I have the problem thats my programm Gui was closed. For example I put this code in a pushButtonClicked method:

database->addDatabase("QMYSQL", "conn1");
database->setHostName("127.0.0.1");
database->setPort(3306);
database->setDatabaseName( "mydb" );
database->setUserName("root");
database->setPassword("XXXX");
if ( !database->open() )
{
    qDebug("Couldn't open DB");
}

It views my Gui, but when I click the button, it closes the window.
When I put this code in an init-method, it doesn't view a window.
What's wrong on this code?
The database is a QSqlDatabase. I declare it in my header.
When I delete this code, everything works normally.

Exa
  • 4,020
  • 7
  • 43
  • 60
thelittlePanda
  • 101
  • 2
  • 10

1 Answers1

0

QSqlDatabase::addDatabase is a static function. The correct form of using it is :

database = QSqlDatabase::addDatabase("QMYSQL", "conn1");

Also note that you should use a variable of type QSqlDatabase as a class member not a pointer to QSqlDatabase.

Nejat
  • 31,784
  • 12
  • 106
  • 138
  • You can define `database` as a class member like `QSqlDatabase database`. Why are you using a pointer to `QSqlDatabase`? – Nejat Sep 18 '14 at 08:04
  • yes, i have delete the pointer ;) now it works so but cant open my db – thelittlePanda Sep 18 '14 at 08:06
  • Ok at-least one of your problems is solved now. This that you can not open database may be due to many reasons. May be you have not the relevant driver. Or you are not defining the correct database name, user or password. Perhaps the database server is not running. – Nejat Sep 18 '14 at 08:14
  • Try to see the output of `database.lastError().driverText()`. – Nejat Sep 18 '14 at 08:15
  • i have looking in the terminal, the server is running and in my terminal i can open my db. so its the right password, name and username. – thelittlePanda Sep 18 '14 at 08:18
  • model->setQuery("SELECT id, Nachname, Vorname, Ort FROM testtable"); this makes the error. – thelittlePanda Sep 18 '14 at 08:18
  • You should make sure that the database is open before making queries. Try to see the driver error text if `database.open()` fails. – Nejat Sep 18 '14 at 08:22
  • .driverText(); dont works. "driverText could not be resolved" – thelittlePanda Sep 18 '14 at 08:32
  • Try `database.lastError().text()` – Nejat Sep 18 '14 at 09:01