使用switch语句时丢失了与数据库的连接

时间:2011-05-13 18:49:38

标签: c++ database qt qt4 switch-statement

我有stackedwidget有多个页面,在第一页,我检查连接,第二页,我检查用户的可用性,依此类推剩下的页面(我有五个),基本上,其他页面依赖于第一页,如果连接失败或者没有,我的问题是关于其他页面,即使连接没有任何错误,第二页也无法进行查询,我收到此错误:

QSqlQuery::prepare: database not open

我的插槽:

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"), trUtf8("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;
     }
}

连接:

connect(ui->nextButton0, SIGNAL(clicked()), this, SLOT(setNextPage()));
connect(ui->nextButton1, SIGNAL(clicked()), this, SLOT(setNextPage()));
//etc

1 个答案:

答案 0 :(得分:0)

来自文档:

  

警告:您必须加载SQL驱动程序   然后打开连接   QSqlQuery已创建。而且,   连接必须保持打开状态   查询存在;否则,行为   QSqlQuery未定义。

所以我必须在每个QSqlQuery query声明中声明case变量,现在我的问题已经解决了。