Hi everyone,
I am trying mysql database connection with QSqlDatabase and it's behaving really strange. When I have only one button in the GUI, everything works fine. But when I add Line Edit, which doesn't do anything, program hangs for about 4 seconds on exit.
Only thing the program does is that it creates connection to database in constructor and then closes it in destructor.
Here is the code:
MainWindow
::MainWindow(QWidget *parent
) : ui(new Ui::MainWindow)
{
ui->setupUi(this);
db.setHostName("127.0.0.1");
db.setDatabaseName("db");
db.setUserName("user");
db.setPassword("password");
connected = db.open();
}
MainWindow::~MainWindow()
{
db.close();
delete ui;
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
db = QSqlDatabase::addDatabase("QMYSQL", "connection");
db.setHostName("127.0.0.1");
db.setDatabaseName("db");
db.setUserName("user");
db.setPassword("password");
connected = db.open();
}
MainWindow::~MainWindow()
{
db.close();
db = QSqlDatabase();
QSqlDatabase::removeDatabase("connection");
delete ui;
}
To copy to clipboard, switch view to plain text mode
If I put this code in "on_pushButton_clicked()" function, program exits correctly. But is it okay to create and remove connection to database in every function of the program, when I want to create more complex database solution?
Another strange thing is that I had to add "db = QSqlDatabase();" before I call removeDatabase, because it showed warning about connection being used when program exited.
Is someone here who can explain it to me, please?
Bookmarks