Lost the connection to database when using switch statment
I have stackedwidget
with multiple pages, at page one, I check the connection, page two, I check the availability of user, and so on for the rest of page(I have five), basically, other pages depend in the first page, if the connection failed or not, my problem is about other pages, even the connection made with out any errors, the second page can't made its query, I am getting this error:
QSqlQuery::prepare: database not open
My slot:
void ConfSetup::setNextPage()
{
int currentIndex = ui->stackedWidget->currentIndex();
switch(currentIndex)
{
case 1:
ui->stackedWidget->setCurrentIndex(currentIndex + 1);
break;
case 2:
db = QSqlDatabase::addDatabase("QMYSQL");
db.setDatabaseName("mysql");
db.setHostName(ui->serverEdit->text());
db.setPort(ui->portEdit->text().toInt());
db.setUserName(ui->userEdit->text());
db.setPassword(ui->passwordEdit->text());
if(!db.open())
{
QMessageBox::critical(0, trUtf8("Fail to login"), tr开发者_如何转开发Utf8("Wrong user or password"));
}
else
ui->stackedWidget->setCurrentIndex(currentIndex + 1);
break;
case 3:
query.prepare("SELECT user FROM user WHERE user=:user");
query.bindValue(":user", ui->userDbEdit->text());
query.exec();
if(query.numRowsAffected() == 1)
QMessageBox::critical(0, trUtf8("User exist"), trUtf8("This user already token"));
else
ui->stackedWidget->setCurrentIndex(currentIndex + 1);
break;
case 4:
query.prepare("SELECT SCHEMA_NAME AS 'Database' FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=:database");
query.bindValue(":database", ui->dbNameEdit->text());
query.exec();
if(query.numRowsAffected() == 1)
QMessageBox::critical(0, trUtf8("Fail to create database"), trUtf8("This database already exist"));
else
ui->stackedWidget->setCurrentIndex(currentIndex + 1);
break;
}
}
The connection:
connect(ui->nextButton0, SIGNAL(clicked()), this, SLOT(setNextPage()));
connect(ui->nextButton1, SIGNAL(clicked()), this, SLOT(setNextPage()));
//etc
From the documentation:
Warning: You must load the SQL driver and open the connection before a QSqlQuery is created. Also, the connection must remain open while the query exists; otherwise, the behavior of QSqlQuery is undefined.
So I have to declare QSqlQuery query
variable at each case
statment, now my problem solved.
精彩评论