当前位置: 首页>>代码示例>>C++>>正文


C++ QSqlQuery::prepare方法代码示例

本文整理汇总了C++中QSqlQuery::prepare方法的典型用法代码示例。如果您正苦于以下问题:C++ QSqlQuery::prepare方法的具体用法?C++ QSqlQuery::prepare怎么用?C++ QSqlQuery::prepare使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QSqlQuery的用法示例。


在下文中一共展示了QSqlQuery::prepare方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: import


//.........这里部分代码省略.........
        if(nI)
        {
            for(int k=0;k<=nI;k++)
            {
            cap.V=sArray[1].points[k].V;
            cap.X=sArray[1].points[k].X;
            cap.Y=sArray[1].points[k].Y;
            sArray[1].points[k].V=sArray[1].points[sArray[1].nmax].V;
            sArray[1].points[k].X=sArray[1].points[sArray[1].nmax].X;
            sArray[1].points[k].Y=sArray[1].points[sArray[1].nmax].Y;
            sArray[1].points[sArray[1].nmax].V=cap.V;
            sArray[1].points[sArray[1].nmax].X=cap.X;
            sArray[1].points[sArray[1].nmax].Y=cap.Y;
            sArray[1].nmax=k+1;
            for(int i=k+1 ; i < sArray[1].n ; i++)
                if(sArray[1].points[sArray[1].nmax].V < sArray[1].points[i].V)
                    sArray[1].nmax=i;
            }
        }
        if(nQ)
        {
            for(int k=0;k<=nQ;k++)
            {
            cap.V=sArray[2].points[k].V;
            cap.X=sArray[2].points[k].X;
            cap.Y=sArray[2].points[k].Y;
            sArray[2].points[k].V=sArray[2].points[sArray[2].nmax].V;
            sArray[2].points[k].X=sArray[2].points[sArray[2].nmax].X;
            sArray[2].points[k].Y=sArray[2].points[sArray[2].nmax].Y;
            sArray[2].points[sArray[2].nmax].V=cap.V;
            sArray[2].points[sArray[2].nmax].X=cap.X;
            sArray[2].points[sArray[2].nmax].Y=cap.Y;
            sArray[2].nmax=k+1;
            for(int i=k+1 ; i < sArray[2].n ; i++)
                if(sArray[2].points[sArray[2].nmax].V < sArray[2].points[i].V)
                    sArray[2].nmax=i;
            }
        }
        //qDebug()<<time.elapsed();
        //_______________ Ok now we have 60 main points, lets transform it in sign______________
        Sign sign[3];
        for(int i=0;i<nY;i++)
        {
            sign[0].points[i].V = (yiq[0][sArray[0].points[i].X][sArray[0].points[i].Y].Y > 0) ? 1 : -1;
            sign[0].points[i].X = sArray[0].points[i].X;
            sign[0].points[i].Y = sArray[0].points[i].Y;
        }
        for(int i=0;i<nI;i++)
        {
            sign[1].points[i].V = (yiq[0][sArray[1].points[i].X][sArray[1].points[i].Y].I > 0) ? 1 : -1;
            sign[1].points[i].X = sArray[1].points[i].X;
            sign[1].points[i].Y = sArray[1].points[i].Y;
        }
        for(int i=0;i<nQ;i++)
        {
            sign[2].points[i].V = (yiq[0][sArray[2].points[i].X][sArray[2].points[i].Y].Q > 0) ? 1 : -1;
            sign[2].points[i].X = sArray[2].points[i].X;
            sign[2].points[i].Y = sArray[2].points[i].Y;
        }

        QSqlQuery q;
        q.prepare(QLatin1String("INSERT INTO images(genreId, bigPath, smallPath,Y,I,Q) VALUES (1,'C:/1.jpg','C:/2.jpg',?,?,?)"));
        q.addBindValue(yiq[0][0][0].Y);
        q.addBindValue(yiq[0][0][0].I);
        q.addBindValue(yiq[0][0][0].Q);
        q.exec();
        int id=q.lastInsertId().toInt();
        q.prepare(QLatin1String("INSERT INTO Y(imageId, x, y, sign) VALUES (?,?,?,?)"));

        for(int i=0;i<nY;i++)
        {
            q.addBindValue(id);
            q.addBindValue(sign[0].points[i].X);
            q.addBindValue(sign[0].points[i].Y);
            q.addBindValue(sign[0].points[i].V);
            q.exec();
        }
        q.prepare(QLatin1String("INSERT INTO I(imageId, x, y, sign) VALUES (?,?,?,?)"));
        for(int i=0;i<nI;i++)
        {
            q.addBindValue(id);
            q.addBindValue(sign[1].points[i].X);
            q.addBindValue(sign[1].points[i].Y);
            q.addBindValue(sign[1].points[i].V);
            q.exec();
        }
        q.prepare(QLatin1String("INSERT INTO Q(imageId, x, y, sign) VALUES (?,?,?,?)"));
        for(int i=0;i<nQ;i++)
        {
            q.addBindValue(id);
            q.addBindValue(sign[2].points[i].X);
            q.addBindValue(sign[2].points[i].Y);
            q.addBindValue(sign[2].points[i].V);
            q.exec();
        }
        //qDebug()<<QString("/cache/%1.jpg").arg(id);

        img.save(QString("cache/%1.jpg").arg(id));

    }
开发者ID:Chetter2,项目名称:WImageRecognition,代码行数:101,代码来源:mainwindow.cpp

示例2: insertBubble

bool DatabaseManager::insertBubble(int type, int number, std::vector<bubblePoint> bubble)
{

    // bool ret = false;

    if (db.isOpen())
    {

        QSqlQuery query;

        //  query.exec("PRAGMA journal_mode = MEMORY");
        //  query.exec("PRAGMA synchronous = OFF");
        query.prepare(QString("replace into bubble values( ?, ?, ?, ?, ?, ?)"));

        //    query.prepare(QString("insert into bubble values( :type, :number, :pan, :tilt, :val) ON DUPLICATE KEY update val = :val)"));

        //    updateQuery.prepare("update bubble set val = :val where type = %type and number = %2 and pan = %3 and tilt = %4");
        QVariantList typee;
        QVariantList numberr;
        QVariantList placeLabel;
        QVariantList pan;
        QVariantList tilt;
        QVariantList val;

        db.transaction();

        // Insert new bubble
        for(uint i = 0; i < bubble.size(); i++)
        {

            bubblePoint pt;

            pt = bubble.at(i);

            typee<<type;
            numberr<<number;
            pan<<pt.panAng;
            tilt<<pt.tiltAng;
            val<<pt.val;

            if(placeLabels.size() >= number)
            {
                placeLabel<<placeLabels.at(number-1);
            }

            else
                placeLabel<<-1;


            /*      query.bindValue(":type",type);
                 query.bindValue(":number",number);
                  query.bindValue(":pan",pt.panAng);
                   query.bindValue(":tilt",pt.tiltAng);
                   query.bindValue(":val",pt.val);*/
            //  query.exec();

            //query.exec(QString("insert into bubble values('%1', '%2', '%3', '%4', %5)").arg(type).arg(number).arg(pt.panAng).arg(pt.tiltAng).arg(pt.val));


        }



        query.addBindValue(typee);
        query.addBindValue(numberr);
        query.addBindValue(placeLabel);
        query.addBindValue(pan);
        query.addBindValue(tilt);
        query.addBindValue(val);


        if (!query.execBatch())
            qDebug() << query.lastError();

        db.commit();

        return true;

    }



    return false;



}
开发者ID:hkaraoguz,项目名称:placeDetectionISL,代码行数:87,代码来源:databasemanager.cpp

示例3: writeToDB

int LoadAppScript::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg)
{
  if (_name.isEmpty())
  {
    errMsg = TR("<font color=orange>The script does not have"
                         " a name.</font>");
    return -1;
  }

  if (pdata.isEmpty())
  {
    errMsg = TR("<font color=orange>The script %1 is empty.</font>")
                         .arg(_filename);
    return -2;
  }

  if (_grade == INT_MIN)
  {
    QSqlQuery minOrder;
    minOrder.prepare("SELECT MIN(script_order) AS min "
                     "FROM script "
                     "WHERE (script_name=:name);");
    minOrder.bindValue(":name", _name);
    minOrder.exec();
    if (minOrder.first())
      _grade = minOrder.value(0).toInt();
    else if (minOrder.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = minOrder.lastError();
      errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
      return -3;
    }
    else
      _grade = 0;
  }
  else if (_grade == INT_MAX)
  {
    QSqlQuery maxOrder;
    maxOrder.prepare("SELECT MAX(script_order) AS max "
                     "FROM script "
                     "WHERE (script_name=:name);");
    maxOrder.bindValue(":name", _name);
    maxOrder.exec();
    if (maxOrder.first())
      _grade = maxOrder.value(0).toInt();
    else if (maxOrder.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = maxOrder.lastError();
      errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
      return -4;
    }
    else
      _grade = 0;
  }

  QSqlQuery select;
  QSqlQuery upsert;

  int scriptid  = -1;
  int pkgheadid = -1;
  int pkgitemid = -1;
  if (pkgname.isEmpty())
    select.prepare(QString("SELECT script_id, -1, -1"
                         "  FROM %1script "
                         " WHERE ((script_name=:name)"
                         "   AND  (script_order=:grade));")
                       .arg(_system ? "" : "pkg"));
  else
    select.prepare(_pkgitemQueryStr);
  select.bindValue(":name",    _name);
  select.bindValue(":pkgname", pkgname);
  select.bindValue(":grade",   _grade);
  select.bindValue(":type",    _pkgitemtype);
  select.exec();
  if(select.first())
  {
    scriptid  = select.value(0).toInt();
    pkgheadid = select.value(1).toInt();
    pkgitemid = select.value(2).toInt();
  }
  else if (select.lastError().type() != QSqlError::NoError)
  {
    QSqlError err = select.lastError();
    errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
    return -5;
  }

  if (scriptid >= 0)
  upsert.prepare(QString("UPDATE %1script "
                         "   SET script_order=:grade, "
                         "       script_enabled=:enabled,"
                         "       script_source=:source,"
                         "       script_notes=:notes "
                         " WHERE (script_id=:id); ")
                       .arg(_system ? "" : "pkg"));
  else
  {
    upsert.prepare("SELECT NEXTVAL('script_script_id_seq');");
    upsert.exec();
    if (upsert.first())
//.........这里部分代码省略.........
开发者ID:gpazo,项目名称:xtuple-svn,代码行数:101,代码来源:loadappscript.cpp

示例4: transitions

/**
 * @brief eine Transition wird anhand der Eingabe durchgefuehrt
 * Die IDs der Zustaende idle(IDLE), selected(SELECTED), amountset(AMOUNTSET) und finished(FINISHED) werden gesetzt.
 * 
 * Anhand der ID des aktuellen Zustandes wird entschieden:
 * -IDLE: Anhand der Eingabe wird entschieden:
 *		 *SELECT: Der neue Zustand ist selected. Die Produkt ID wird (Aufruf getDetectedPid()) bestimmt.
 *		 *sonst: Fehlermeldung
 * -SELECTED: Anhand der Eingabe wird entschieden:
 *		 *ONE: Der neue Zustand ist amountset. Die Produktmenge ist 1.
 *		 *TWO: Der neue Zustand ist amountset. Die Produktmenge ist 2.
 *		 *BACK: Der neue Zustand ist idle.
 *		 *CANCEL: Der neue Zustand ist idle.
 *		 *sonst: Fehlermeldung
 * -AMOUNTSET: Anhand der Eingabe wird entschieden:
 *		 *PUTINCART: der neue Zustand ist finished. Das Produkt wird in den Warenkorb abgelegt.
 *		 *BACK: der neue Zustand ist selected. Die Produkt Menge wird zurueckgesetzt.
 *		 *CANCEL: der neue Zustand ist idle. Die Produkt Menge wird zurueckgesetzt.
 *		 *sonst: Fehlermeldung
 * -FINISHED: Anhand der Eingabe wird entschieden:
 *		 *MORE: der neue Zustand ist idle. Die Produkt Menge wird zurueckgesetzt.
 *		 *sonst: Fehlermeldung
 * @param input Eine Zahl, von der abhaengig ist, welche Aktion als naechstes ausgefuehrt wird.
 * @return void
 * @see IDLE 0
 * @see SELECTED 1
 * @see AMOUNTSET 2
 * @see FINISHED 3
 * @see ONE 1
 * @see TWO 2
 * @see SELECT 100
 * @see PUTINCART 101
 * @see BACK 102
 * @see CANCEL 103
 * @see MORE 104
 */
void automaton::transitions(int input){

    idle.setId(IDLE);
    selected.setId(SELECTED);
    amountset.setId(AMOUNTSET);
    finished.setId(FINISHED);

    QMessageBox msgBox;
    msgBox.setText("Die StateId ist: "+QString::number(currentState.getId())+"\nDer Input ist: "+QString::number(input));
    msgBox.exec();

    switch (currentState.getId()){

    case IDLE:
        switch (input) {
        case SELECT:
            // neue pid hier setzen
            setState(selected);
            this->setPid(connectedKinect->getDetectedPid());
            break;
        default:
            qDebug() << "FEHLER: case IDLE";
            break;
        }
    break;

    case SELECTED:
        switch (input) {
        case ONE:
            setState(amountset);
            setAmount(1);
            break;
        case TWO:
            setState(amountset);
            setAmount(2);
            break;
        case BACK:
            setState(idle);
            break;
        case CANCEL:
            setState(idle);
            break;
        default:
            qDebug() << "FEHLER: case SELECTED";
            break;
        }
    break;

    case AMOUNTSET:
        switch (input) {
        case PUTINCART:
        {
            setState(finished);
            QSqlQuery query;
            query.prepare("SELECT price, title FROM products WHERE id = :pid");
            query.bindValue(":pid", pid);
            query.exec();
            query.next();
            double price = query.value(0).toDouble();
            QString title = query.value(1).toString();
            connectedObj->addToCart(pid,amount,price,title);
            break;
        }
        case BACK:
//.........这里部分代码省略.........
开发者ID:tangboshi,项目名称:kinectshop,代码行数:101,代码来源:automaton.cpp

示例5: setFrameDetails

void FrmFrameDetails::setFrameDetails(const Mode mode, const Persistence persistence, Sample* sample, 
                                      QList<int>& blackList, const Options options)
{
    qApp->setOverrideCursor( QCursor(Qt::BusyCursor ) );

    if (treeView==0) return;

    if (blackList.size()>0)
        treeView->setBlackList(blackList);

    treeView->setSupportNewItems(options & FrmFrameDetails::ALLOW_NEW);

    m_sample=sample;
    m_mode=mode;
    m_persistence=persistence;
    m_verified=false;
    m_submitted=false;

    //Now fix the UI
    lbPersistence->setText
        (persistence==FrmFrameDetails::PERMANENT?tr("Permanent"):tr("Temporary"));

    pushVerify->setEnabled(true);
    pushApply->setEnabled(!pushVerify->isEnabled());
    pushUndo->setEnabled(!pushVerify->isEnabled());

    pushVerify->setVisible(mode!=FrmFrameDetails::VIEW || persistence==FrmFrameDetails::TEMPORARY);
    pushApply->setVisible(mode!=FrmFrameDetails::VIEW || persistence==FrmFrameDetails::TEMPORARY);
    pushUndo->setVisible(mode!=FrmFrameDetails::VIEW || persistence==FrmFrameDetails::TEMPORARY);
    pushBack->setVisible(true);

    lineName->clear();
    textComments->clear();
    textDesc->clear();

    if (!initModel(mode,sample,options)){
        qApp->setOverrideCursor( QCursor(Qt::ArrowCursor ) );
        emit showError(tr("Could not create frame view!"));
        return;
    }

    if (mode==FrmFrameDetails::VIEW){// read-only on Permanent mode
        groupBox->setEnabled(false);
        setTreeReadOnly(true);
        horizontalLayout->addWidget(pushBack);
        persistence==FrmFrameDetails::PERMANENT? horizontalLayout->removeWidget(pushVerify):horizontalLayout->addWidget(pushVerify);
        persistence==FrmFrameDetails::PERMANENT? horizontalLayout->removeWidget(pushApply): horizontalLayout->addWidget(pushApply);
        persistence==FrmFrameDetails::PERMANENT? horizontalLayout->removeWidget(pushUndo): horizontalLayout->addWidget(pushUndo);

        persistence==FrmFrameDetails::PERMANENT?setTreeReadOnly(true):setTreeReadOnly(false);

        initMapper();//TODO: maybe throw an error here later?
        modelInterface->tRefFrame->setFilter(tr("Fr_Frame.ID=") + QVariant(sample->frameId).toString());
        mapper->toLast();

    }else{
        if (!modelInterface->insertNewRecord(modelInterface->tRefFrame)){
            qApp->setOverrideCursor( QCursor(Qt::ArrowCursor ) );
            QString strErrors;
            if (modelInterface->getErrors(strErrors))
                emit showError(strErrors);
            else
                emit showError(tr("Could not insert new record!"));
        }else{
            initMapper();//TODO: maybe throw an error here later?
            mapper->toLast();

            if (mode==FrmFrameDetails::EDIT){
                //set Frame Name
                QSqlQuery query;
                query.prepare(tr("SELECT dbo.FR_Frame.Name FROM dbo.FR_Frame ") + 
                              tr("WHERE     (dbo.FR_Frame.ID = ?)"));
                query.addBindValue(sample->frameId);
                if (!query.exec() || query.numRowsAffected()<1){
                    qApp->setOverrideCursor( QCursor(Qt::ArrowCursor ) );
                    if (query.lastError().type()!=QSqlError::NoError)
                        emit showError(query.lastError().text());
                    else
                        emit showError(tr("Could not retrieve the type of the cloned frame!"));
                    return;
                }
                query.first();
                this->cmbCloned->setCurrentIndex(this->cmbCloned->findText(
                    query.value(0).toString()));

                //Set src ID
                query.prepare(tr("SELECT dbo.Ref_Source.Name FROM dbo.FR_Frame INNER JOIN ") + 
                              tr("dbo.Ref_Source ON dbo.FR_Frame.id_source = dbo.Ref_Source.ID ") +
                              tr("WHERE     (dbo.FR_Frame.ID = ?)"));
                query.addBindValue(sample->frameId);
                if (!query.exec() || query.numRowsAffected()<1){
                    qApp->setOverrideCursor( QCursor(Qt::ArrowCursor ) );
                    if (query.lastError().type()!=QSqlError::NoError)
                        emit showError(query.lastError().text());
                    else
                        emit showError(tr("Could not retrieve the type of the cloned frame!"));
                    return;
                }
                query.first();

//.........这里部分代码省略.........
开发者ID:doublebyte1,项目名称:medfisis_nix,代码行数:101,代码来源:frmframedetails.cpp

示例6: saveDatabaseTimeRecord

bool DataManager::saveDatabaseTimeRecord(Map map) {
    qDebug("DataManager::saveDatabaseTimeRecord");
    QString userName;

#if defined(UNICODE)
    if ( QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)
    {
        TCHAR winUserName[UNLEN + 1]; // UNLEN is defined in LMCONS.H
        DWORD winUserNameSize = sizeof(winUserName);
        GetUserName( winUserName, &winUserNameSize );
        userName = QString::fromWCharArray( winUserName );
    } else
#endif
    {
        char winUserName[UNLEN + 1]; // UNLEN is defined in LMCONS.H
        DWORD winUserNameSize = sizeof(winUserName);
        GetUserNameA( winUserName, &winUserNameSize );
        userName = QString::fromLocal8Bit( winUserName );
    }

    qDebug("DataManager::saveDatabaseTimeRecord windows user: %s", userName.toStdString().c_str());
    QString userGuid;
    std::string userGuidSql = "select id from dbo.CoreUser where AccountName = 'VIS_BOG_HQ\\" + userName.toStdString() + "'";
    QSqlQuery sqlUserGuid(QString(userGuidSql.c_str()));
    if (sqlUserGuid.next()) {
        userGuid = sqlUserGuid.value(0).toString();
        qDebug("DataManager::saveDatabaseTimeRecord user guid: %s", userGuid.toStdString().c_str());
    } else {
        qDebug("User %s not found", userName.toStdString().c_str());
        return false;
    }

    int periodId = period(map.date.toQDateTime());
    qDebug("DataManager::saveDatabaseTimeRecord period id: %d", periodId);
    if (periodId == -1) {
        return false;
    }

    int displayOrder = 1;
    QSqlQuery displayOrderSql;
    if (displayOrderSql.prepare("select Max(displayOrder) from dbo.TimeEntry where PeriodId = :Period and CoreUserId = :CoreUserId")) {
        displayOrderSql.bindValue(":Period", periodId);
        displayOrderSql.bindValue(":CoreUserId", userGuid);
        if (displayOrderSql.exec() && displayOrderSql.next()) {
            displayOrder = displayOrderSql.value(0).toInt() + 1;
        } else {
            displayOrder = 1;
        }
    } else {
        qDebug("Error getting the displayOrder");
        return false;
    }
    qDebug("DataManager::saveDatabaseTimeRecord displayOrder: %d", displayOrder);
    std::stringstream ssSql;
    ssSql << "INSERT INTO TimeEntry (PeriodId,ProjectId,TaskId,CoreUserId,Date,Hours,Description,UpdatedOn,DisplayOrder,Version)";
    ssSql << " VALUES (:PeriodId,:ProjectId,:TaskId,:CoreUserId,:Date,:Hours,:Description,:UpdatedOn,:DisplayOrder,:Version)";
    QSqlQuery insert;
    insert.prepare(QString(ssSql.str().c_str()));
    insert.bindValue(":PeriodId", periodId);
    insert.bindValue(":ProjectId", map.coreProject.id);
    insert.bindValue(":TaskId", map.coreTask.id);
    insert.bindValue(":CoreUserId", userGuid);
    insert.bindValue(":Date", map.date.toQDateTime());
    double minutes = ((double)((int)(map.time.totalMinutes() * 100))/(double)100);

    insert.bindValue(":Hours", minutes);
    insert.bindValue(":Description", map.description);
    insert.bindValue(":UpdatedOn", QDateTime::currentDateTime());
    insert.bindValue(":DisplayOrder", displayOrder);
    insert.bindValue(":Version", 2);
    bool updated = insert.exec();
    if (!updated) {
        qDebug("An error has ocurred executing the insertion. Error: %s", insert.lastError().text().toStdString().c_str());
    }

    qDebug("out DataManager::saveDatabaseTimeRecord");
    return updated;
}
开发者ID:crossleyjuan,项目名称:djon,代码行数:78,代码来源:datamanager.cpp

示例7: on_pushButton_Login_clicked

void Login::on_pushButton_Login_clicked()
{

    QString username = ui->lineEdit_username->text();
    QString password = ui->lineEdit_password->text();
    QSqlQuery query;
    QString employID;
    QString isTempPass;
    QString islocked;
    roleSel *roleDash = new roleSel();
    query.bindValue(":username", username);
    query.bindValue(":password", password);
    bool debug = true;

    if (debug)
    {
        if ((username == "root") & (password == "root"))
        {
            accountCreate *ACDash = new accountCreate();
            this->close();
            ACDash->show();
            ACDash->activateWindow();
            ACDash->raise();
        }
    }
    setLoginCount(username);

                //checks login if correct
                query.prepare("SELECT * FROM Account WHERE accountID = '"+username+"' and password = '"+password+"'");
                if (query.exec())
                {
                    qDebug()<<"Code has entered login check";
                    int count=0;
                    while(query.next())
                    {
                        employeeID = query.value(1).toString();
                       // qDebug()<<"I have entered this";
                        isTempPass = query.value(6).toString();
                        islocked = query.value(7).toString();
                        count++;
                        qDebug()<<"The count is: "<<count;
                     }
                     if (count==1)
                     {
                        ui->label_status->setText("Login Successful");

                        //user needs to change password because current is temporary
                        if (isTempPass == "1")
                        {
                            changePass *passDash = new changePass();
                            QObject::connect(this, SIGNAL(sendData(QString)), &*passDash, SLOT(receiveData(QString)));
                            emit sendData(employeeID);
                            passDash->setModal(true);
                            passDash->show();
                            passDash->activateWindow();
                            passDash->raise();
                        }
                        else //information is correct
                        {
                            //check if account is locked
                            if (islocked == "1")
                            {
                                QMessageBox msgbox;
                                msgbox.setText("Your Account is locked, please see a system administrator");
                                msgbox.exec();
                            }
                            //account is not locked
                            else
                            {
                                QObject::connect(this, SIGNAL(sendData(QString)), &*roleDash, SLOT(receiveData(QString)));
                                qDebug()<<"Sending data: "<<employeeID;
                                qDebug()<<"Temporary pass is: "<<isTempPass;
                                emit sendData(employeeID);
                                query.prepare("UPDATE Account SET loginCountID = '0' FROM Account WHERE accountID = '"+username+"'");
                                if(query.exec())
                                {
                                     qDebug()<<"The loginCount being reset to is : "<<loginCount;
                                     ui->label_loginCount->setText("");
                                }
                                this->hide();
                                roleDash->show();
                                roleDash->activateWindow();
                                roleDash->raise();
                            }
                        }
                      }
                        //login information is incorrect
                        if (count<1)
                        {
                            qDebug()<<"Code has entered the fail to vertify section";
                            ui->label_status->setText("username or password is incorrect");
                            //check if loginCount has been maxed
                            //if loginCount is over 6 then lock the account
                            if (loginCount >6)
                            {
                                QMessageBox msgbox;
                                msgbox.setText("You have failed to login 6 times, your account is now locked. "
                                                 "Please see the system administrator for further assistance");
                                query.prepare("UPDATE Account SET islocked = '1' FROM Account WHERE accountID = '"+username+"'");
                                query.exec();
//.........这里部分代码省略.........
开发者ID:wjanpong,项目名称:Streamlined-Grading-System,代码行数:101,代码来源:login.cpp

示例8: main


//.........这里部分代码省略.........
                            if( res.get_language_count( L"TEXT", qid ) > 1 )
                                info = res.get_resource_data_by_id( 0, L"TEXT", qid );
                            else
                                info = res.get_resource_data_by_id( 1049, L"TEXT", qid );

                            std::string raw( info.get_data() );
                            question.set_task_and_answers(codec->toUnicode(raw.c_str()));
                        }

                        // комментарий
                        {
                            resource_data_info info( "", 0 );
                            if( resComment.get_language_count( L"TEXT", qid ) > 1 )
                                info = resComment.get_resource_data_by_id( 0, L"TEXT", qid );
                            else
                                info = resComment.get_resource_data_by_id( 1049, L"TEXT", qid );

                            std::string raw( info.get_data() );
                            question.comment = codec->toUnicode(raw.c_str()).replace("\n", " ");
                        }
                    }

                    { // Названия тем
                        resource_data_info info = res.get_resource_data_by_id(1049, L"THEME_NAME", 1050 + t);
                        themes[t].name = codec->toUnicode(info.get_data().c_str());
                    }
                }
            }

        } catch( const pe_exception& e ) { //Если возникла ошибка
            std::cout << e.what() << std::endl;
            return EXIT_FAILURE;
        }

        // Данные из PE файлов загружены. Формируем таблицы новой базы данных

        for(uint t = 0; t < themes.size(); ++t) {
            QSqlQuery addTheme;
            addTheme.prepare(QString("INSERT INTO themes_%1"\
                             "(theme_num, name, quest_count)"\
                             " VALUES"\
                             "(:theme_num, :name, :quest_count);").arg(category_name));

            addTheme.bindValue(":theme_num", t+1);
            addTheme.bindValue(":name", themes[t].name);
            addTheme.bindValue(":quest_count", themes[t].questions.size());

            if(!addTheme.exec()) {
                std::cout << addTheme.lastError().text().toStdString() << std::endl;
            }
        }

        uint i = 1;
        for(uint t = 0; t < themes.size(); ++t) {

            uint in_theme_num = 1;
            Questions& questions = themes[t].questions;
            for(Questions::iterator q = questions.begin(); q != questions.end(); ++q) {
                QSqlQuery addQuestion;
                addQuestion.prepare(QString("INSERT INTO questions_%1"\
                                    "(number, task, vars_count, right_ans, comment, ans_v1, ans_v2, ans_v3, ans_v4, ans_v5, image, theme_num, in_theme_num)"
                                    "VALUES"\
                                    "(:number, :task, :vars_count, :right_ans, :comment, :ans_v1, :ans_v2, :ans_v3, :ans_v4, :ans_v5, :image, :theme_num, :in_theme_num);").arg(category_name));

                addQuestion.bindValue(":number", i++);
                addQuestion.bindValue(":task", q->task);
                QStringList& answers = q->answers;
                uint vars_count = answers.size();
                addQuestion.bindValue(":vars_count", vars_count);
                addQuestion.bindValue(":right_ans", q->answer);
                addQuestion.bindValue(":comment", q->comment);

                for(uint v = 0; v < vars_count; ++v) {
                    addQuestion.bindValue(QString(":ans_v%1").arg(v+1), answers[v]);
                }

                for(uint k = vars_count; k < 6; ++k) {
                    addQuestion.bindValue(QString(":ans_v%1").arg(k+1), "");
                }

                addQuestion.bindValue(":image", q->imageName);
                addQuestion.bindValue(":theme_num", q->themeNumber+1);
                addQuestion.bindValue(":in_theme_num", in_theme_num++);

                if(!addQuestion.exec()) {
                    std::cout << addQuestion.lastError().text().toStdString() << std::endl;
                } else {
                    std::cout << category_name.toStdString() << " add question " << i-1 << std::endl;
                }
            }
        }

        if(category_name == "ab") category_name = "cd";
        else category_name = "";

    } while(category_name != "");

    std::cout << "Complited." << std::endl;
    return app.exec();
}
开发者ID:andemeno,项目名称:pdd,代码行数:101,代码来源:main.cpp

示例9: qDebug

void MainWindow::on_pushButton_2_clicked()
{
    if(ui->B_NIO->text().isEmpty() || ui->S_NO->text().isEmpty()){
        QMessageBox::warning(this,tr("提示"),tr("不能为空"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    QSqlQuery query;
    QString s_num="";
    QString b_num="";
    QString o_name="";
    QString o_author="";
    QString o_price ="";
    QString s_name="";
    QString b_id="";
    query.prepare("select C_NUM from  COUNT where C_NO = :uid");
    query.bindValue(":uid",ui->S_NO->text());
    query.exec();
    if(query.next()){
        s_num = query.value(0).toString();
    }
    query.prepare("select * from  BOOKS where O_ISBN = :bid");
    query.bindValue(":bid",ui->B_NIO->text());
    query.exec();
    if(query.next()){
        o_name = query.value(1).toString();
        o_author = query.value(2).toString();
        o_price = query.value(4).toString();
        b_num = query.value(5).toString();
    }
    qDebug()<<s_num<<b_num;
    query.prepare("SELECT S_NAME FROM STUDENTS WHERE S_NO = ?");
    query.addBindValue(ui->S_NO->text());
    query.exec();
    if(query.next()){
        s_name = query.value(0).toString();
        qDebug()<<s_name;
    }
    if(s_num.isEmpty()){
        QMessageBox::warning(this,tr("提示"),tr("输入学号错误"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    if(b_num.isEmpty()){
        QMessageBox::warning(this,tr("提示"),tr("输入ISBN错误"),QMessageBox::Ok);
        ui->B_NIO->clear();
        ui->S_NO->clear();
        return;
    }
    int ss_num=s_num.toInt();
    int bb_num=b_num.toInt();
    ++bb_num;
    ++ss_num;
    qDebug()<<ss_num<<bb_num;
    query.prepare("UPDATE BOOKS SET  O_STORAGE = ? WHERE O_ISBN = ?");
    query.addBindValue(QString::number(bb_num,10));
    query.addBindValue(ui->B_NIO->text());
    query.exec();
    query.prepare("UPDATE COUNT SET  C_NUM = ? WHERE C_NO = ?");
    query.addBindValue(QString::number(ss_num,10));
    query.addBindValue(ui->S_NO->text());
    query.exec();
    QDate date;
    QDate oldDate;
    QString oldDatetem;
    date=date.currentDate();
    QString newdate=date.toString("yyyy.M.d");
    qDebug()<<newdate;
    int countI = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(countI);
    ui->tableWidget->setItem(countI,0,new QTableWidgetItem(ui->S_NO->text()));
    ui->tableWidget->setItem(countI,1,new QTableWidgetItem(s_name));
    ui->tableWidget->setItem(countI,2,new QTableWidgetItem(ui->B_NIO->text()));
    ui->tableWidget->setItem(countI,3,new QTableWidgetItem(o_name));
    ui->tableWidget->setItem(countI,4,new QTableWidgetItem(o_author));
    ui->tableWidget->setItem(countI,5,new QTableWidgetItem(o_price));
    ui->tableWidget->setItem(countI,6,new QTableWidgetItem(QString(tr("还回"))));
    ui->tableWidget->setItem(countI,8,new QTableWidgetItem(newdate));
    query.prepare("SELECT B_ID,B_TIME FROM BORROW WHERE B_NO = ? AND B_ISBN = ? AND B_ISRENT = 0");
    query.addBindValue(ui->S_NO->text());
    query.addBindValue(ui->B_NIO->text());
    query.exec();
    if(query.first()){
        b_id = query.value(0).toString();
        oldDatetem = query.value(1).toString();
        oldDatetem.replace(QString("-"),QString(""));
        qDebug()<<b_id<<oldDatetem;
    }
    query.prepare("UPDATE BORROW SET B_ISRENT=?,B_RENTTIME=? WHERE B_ID = ?");
    query.addBindValue(1);
    query.addBindValue(newdate);
    query.addBindValue(b_id);
    query.exec();
    oldDate=oldDate.fromString(oldDatetem,"yyyyMMdd");
    qDebug()<<oldDate.toString("yyyy.M.d");
    int timeforBorrow = oldDate.daysTo(date);
    if(timeforBorrow > 30){
        qDebug()<<timeforBorrow;
//.........这里部分代码省略.........
开发者ID:hanliumaozhi,项目名称:DBtest,代码行数:101,代码来源:mainwindow.cpp

示例10: on_commandLinkButton_delete_clicked

void SelectUser::on_commandLinkButton_delete_clicked()
{
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "AvisionR - Delete",
                                  "Are you sure you want to DELETE this Employee from your Database?", QMessageBox::Yes|QMessageBox::No);
    if(reply == QMessageBox::Yes)
    {
        {
            Database conn;
            if(!conn.connOpen("Employee"))
            {
                qDebug()<<"Failed to open Data";
                return;
            }

            QSqlQuery * qry = new QSqlQuery(conn.mydb);

            QString queryString;
            QTextStream queryStream(&queryString);

            queryStream << "DELETE FROM Employees WHERE ID = '" << ui->label_id->text() << "'";

            qry->prepare(queryString);

            if(qry->exec())
            {}
            else
            {
                QMessageBox::critical(this, tr("Error"), qry->lastError().text());
            }

            conn.connClose();
        }

        {
            Database conn;
            if(!conn.connOpen("Clock"))
            {
                qDebug()<<"Failed to open Data";
                return;
            }

            QSqlQuery * qry = new QSqlQuery(conn.mydb);

            QString queryString;
            QTextStream queryStream(&queryString);

            queryStream << "DROP TABLE '" << ui->label_id->text() << "'";

            qry->prepare(queryString);

            if(qry->exec())
            {
                thisUser->setup();
                QMessageBox::information(this, tr("AvisionR - Delete"), "Employee Deleted");
            }
            else
            {
                QMessageBox::critical(this, tr("Error"), qry->lastError().text());
            }

            conn.connClose();
        }


        this->hide();
    }
}
开发者ID:anava014,项目名称:AvisionR---Windows-GUI-Application,代码行数:68,代码来源:selectuser.cpp

示例11: addPlurk

void PlurkDbManager::addPlurk(QString plurk_id, QString plurk_type,
                              QString owner_id, QString content,
                              QString is_unread, QString favorite,
                              QString qual_trans, QString res_seen,
                              QString res_cnt, QString posted) {
    QSqlQuery query;
    QString dummy;
    query.exec("SELECT * FROM plurks WHERE plurk_id='" + plurk_id + "'");
    if(query.next()) {
        //Update record
        query.prepare(dummy + "UPDATE plurks SET plurk_type=:plurk_type,"
                      + "content=:content,"
                      + "is_unread=:is_unread,"
                      + "favorite=:favorite,"
                      + "reponses_seen=:res_seen,"
                      + "response_cnt=:res_cnt"
                      + " WHERE plurk_id=:plurk_id");
        query.bindValue(":plurk_type",plurk_type);
        query.bindValue(":content",content);
        query.bindValue(":is_unread",is_unread);
        query.bindValue(":favorite",favorite);
        query.bindValue(":res_seen",res_seen);
        query.bindValue(":res_cnt",res_cnt);
        query.bindValue(":plurk_id",plurk_id);
        query.exec();
    } else {
        //Add record
        query.prepare(dummy + "INSERT INTO plurks("
                      + "plurk_id,"
                      + "plurk_type,"
                      + "owner_id,"
                      + "content,"
                      + "is_unread,"
                      + "favorite,"
                      + "qualifier_translated,"
                      + "responses_seen,"
                      + "response_count,"
                      + "posted) VALUES("
                      + ":plurk_id,"
                      + ":plurk_type,"
                      + ":owner_id,"
                      + ":content,"
                      + ":is_unread,"
                      + ":favorite,"
                      + ":qual_trans,"
                      + ":res_seen,"
                      + ":res_cnt,"
                      + ":posted)");
        query.bindValue(":plurk_id",plurk_id);
        query.bindValue(":plurk_type",plurk_type);
        query.bindValue(":owner_id",owner_id);
        query.bindValue(":content",content);
        query.bindValue(":is_unread",is_unread);
        query.bindValue(":favorite",favorite);
        query.bindValue(":qual_trans",qual_trans);
        query.bindValue(":res_seen",res_seen);
        query.bindValue(":res_cnt",res_cnt);
        query.bindValue(":posted",posted);
        query.exec();
    }
}
开发者ID:brucehsu,项目名称:maemo-plurk,代码行数:61,代码来源:plurkdbmanager.cpp

示例12: c

TableauDeRemplissage::TableauDeRemplissage(int idEvenement, QObject *parent)
    : Etat(tr("Tableau de remplissage"), idEvenement, parent)
{
    QSqlQuery query;
    if (query.prepare("select *"
                      " from tableau_de_remplissage"
                      " where id_evenement=:id_evenement")) {
        query.bindValue(":id_evenement", idEvenement);
        if (query.exec()) {
            // FIXME : ce rapport devrait être une feuille de calcul

            QString symboleAcceptee = "●";
            QString symboleProposee = "◍";
            QString symbolePossible = "○";
            QString symboleManquante = "◌";

            QTextCursor c(this);

            QTextBlockFormat formatDuTitreDeLaLegende;
            formatDuTitreDeLaLegende.setBottomMargin(10);

            QTextCharFormat formatDesCaracteresDuTitreDeLaLegende;
            formatDesCaracteresDuTitreDeLaLegende.setUnderlineStyle(QTextCharFormat::SingleUnderline);

            QTextBlockFormat formatDesBlocsDeLaLegende;

            QTextCharFormat formatDesCaracteresDeLaLegende;

            QTextListFormat formatDeLaListeDeLaLegende;

            QTextBlockFormat formatDuBlocJour;
            formatDuBlocJour.setPageBreakPolicy(QTextFormat::PageBreak_AlwaysBefore);
            formatDuBlocJour.setAlignment(Qt::AlignCenter);
            formatDuBlocJour.setBottomMargin(20);

            QTextCharFormat formatDesCaracteresDuJour;
            formatDesCaracteresDuJour.setFontCapitalization(QFont::Capitalize);
            formatDesCaracteresDuJour.setFontPointSize(14);
            formatDesCaracteresDuJour.setFontWeight(QFont::Bold);

            QTextBlockFormat formatDuBlocTour;
            formatDuBlocTour.setTopMargin(20);

            QTextCharFormat formatDesCaracteresDuTour;
            formatDesCaracteresDuTour.setFontWeight(QFont::Bold);

            QTextBlockFormat formatDuBlocDesResponsables;

            QTextCharFormat formatDesCaracteresDesResponsables;

            QTextBlockFormat formatDuBlocDuRemplissage;

            QTextCharFormat formatDesCaracteresDuRemplissage;

            if (query.first()) {
                c.movePosition(QTextCursor::End);
                c.insertBlock(formatDuTitreDeLaLegende, formatDesCaracteresDuTitreDeLaLegende);
                c.insertText(tr("Légende"));
                c.insertBlock(formatDesBlocsDeLaLegende, formatDesCaracteresDeLaLegende);
                c.insertList(formatDeLaListeDeLaLegende);
                c.insertText(tr("%1 affectation acceptée ou validée").arg(symboleAcceptee));
                c.insertText("\n");
                c.insertText(tr("%1 affectation proposée, en attente d'acceptation").arg(symboleProposee));
                c.insertText("\n");
                c.insertText(tr("%1 affectation possible, à proposer ou valider").arg(symbolePossible));
                c.insertText("\n");
                c.insertText(tr("%1 affectation manquante, reste à créer").arg(symboleManquante));
                QSqlRecord r = query.record();
                do {
                    QDate jour = r.value("debut_tour").toDate();
                    c.insertBlock(formatDuBlocJour, formatDesCaracteresDuJour);
                    c.insertText(QLocale().toString(jour));
                    do {
                        int
                                min = r.value("min").toInt(),
                                max = r.value("max").toInt(),
                                possibles = r.value("nombre_affectations_possibles").toInt(),
                                proposees = r.value("nombre_affectations_proposees").toInt(),
                                acceptees = r.value("nombre_affectations_validees_ou_acceptees").toInt(),
                                trouvees = acceptees + proposees + possibles,
                                manquantes = trouvees < min ? min - trouvees : 0,
                                enTrop = max < trouvees ? trouvees - max : 0;
                        QString responsables = r.value("liste_responsables").toString();
                        c.insertBlock(formatDuBlocTour, formatDesCaracteresDuTour);
                        c.insertText(tr("De %1 à %2 / %3")
                                     .arg(r.value("debut_tour").toTime().toString("H:mm"))
                                     .arg(r.value("fin_tour").toTime().toString("H:mm"))
                                     .arg(r.value("nom_poste").toString())
                                     );
                        if (!responsables.isEmpty()) {
                            c.insertBlock(formatDuBlocDesResponsables, formatDesCaracteresDesResponsables);
                            c.insertText(tr("Responsable(s) : %1").arg(responsables));
                        }
                        c.insertBlock(formatDuBlocDuRemplissage, formatDesCaracteresDuRemplissage);
                        c.insertText(symboleAcceptee.repeated(acceptees));
                        c.insertText(symboleProposee.repeated(proposees));
                        c.insertText(symbolePossible.repeated(possibles));
                        c.insertText(symboleManquante.repeated(manquantes));
                        if (enTrop) c.insertText(tr(" (%n affectation(s) en trop)", "", enTrop));
                        query.next();
//.........这里部分代码省略.........
开发者ID:sebastiendu,项目名称:gestionnairedaffectations,代码行数:101,代码来源:tableauderemplissage.cpp

示例13: documentListing

void DocDigestDetailView::documentListing( TextTemplate *tmpl, int year, int month )
{

    QString minDate;
    QString maxDate;
    if( month > -1 ) {
        QDate theDate(year, month, 1);
        // not a year
        minDate = theDate.toString("yyyy-MM-dd");
        int lastDay = theDate.daysInMonth();
        theDate.setDate(year, month, lastDay);
        maxDate = theDate.toString("yyyy-MM-dd");
    } else {
        // is is a year
        minDate = QString::number(year)+"-01-01";
        maxDate = QString::number(year)+"-12-31";
    }

    // read data in the given timeframe from database
    QSqlQuery q;
    const QString query = QString("SELECT archDocID, ident, MAX(printDate) FROM archdoc WHERE "
                                  "date BETWEEN date('%1') AND date('%2') "
                                  "GROUP BY ident").arg(minDate, maxDate);

    // qDebug() << "***" << query;
    QMap<QString, QPair<int, Geld> > docMatrix;
    q.prepare(query);
    q.exec();
    while( q.next() ) {
       dbID archDocId(q.value(0).toInt());

       const ArchDoc doc(archDocId);
       const QString docType = doc.docType();
       Geld g;
       int n = 0;
       if( docMatrix.contains(docType)) {
           g = docMatrix[docType].second;
           n = docMatrix[docType].first;
       }
       Geld g1 = doc.nettoSum();
       g += g1;
       docMatrix[docType].first = n+1;
       docMatrix[docType].second = g;
     }

    // now create the template

    tmpl->setValue("I18N_AMOUNT", i18n("Amount"));
    tmpl->setValue("I18N_TYPE",   i18n("Type"));
    tmpl->setValue("I18N_SUM",    i18n("Sum"));

    QStringList doctypes = docMatrix.keys();
    doctypes.sort();

    foreach( const QString dtype, doctypes ) {
        qDebug() << "creating doc list for "<<dtype;
        tmpl->createDictionary( "DOCUMENTS" );
        tmpl->setValue("DOCUMENTS", "DOCTYPE", dtype);
        const QString am = QString::number(docMatrix[dtype].first);
        tmpl->setValue("DOCUMENTS", "AMOUNT", am);
        const QString sm = docMatrix[dtype].second.toString(DefaultProvider::self()->locale());
        tmpl->setValue("DOCUMENTS", "SUM", sm);
    }
开发者ID:dragotin,项目名称:kraft,代码行数:63,代码来源:docdigestdetailview.cpp

示例14: writeResults

/*!
  Эта реализация writeResults только для League!
  */
void League::writeResults() {
    //проверяем, мб мы уже записали
QSettings stg (workdir + "/settings.ini", QSettings::IniFormat, this);
bool isbonus = QFile::exists(workdir+"/bonus.ini");
QSettings bonus (workdir +"/bonus.ini", QSettings::IniFormat, this);
qDebug() << "writing final!";
stg.beginGroup("Tournament");
bool wrote  = false;
wrote = stg.value("stored", false).toBool();
qDebug() << wrote;

    QSqlDatabase db = QSqlDatabase::database("players");
    QSqlQuery q(db) ;
    QSqlQuery sq;
    QString team, nick;
    sq.prepare("SELECT nick, displayname, points FROM Teams ORDER by ABS (points)");
    if (!sq.exec()) {qDebug() << "write result error!" << sq.lastError().text();}
    else {qDebug() << "Query done! " << sq.lastQuery();}
    int rank = 0;
    while (sq.next()) {
        qDebug() << rank;
        rank ++;
        QString result;
        if (rank == 1)
            result.append("Чемпион, ");
         else
             result.append(QVariant (rank).toString() + " место, ");

         result.append(sq.value(2).toString() + " очко(а, ов)");
         nick = sq.value(0).toString();
         team = sq.value(1).toString();
         qDebug() << nick << team << result;
        q.prepare("SELECT smallname FROM Players WHERE nick=:nick");
        q.bindValue(":nick", nick);
        if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
q.first();

QString table = q.value(0).toString();
//проверяем
q.prepare("SELECT COUNT (*) FROM "+ table + " WHERE team=:team AND trn=:trn");
      if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
q.first();
if (q.value(0).toInt() == 0) {
q.prepare("INSERT INTO " + table + "(team, result) VALUES (:team, :result)");
q.bindValue(":team", team);
q.bindValue(":trn", _title);
 if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
//здесь будет выдача бонусов
if (isbonus)
{
    int bpoints = bonus.value(QVariant(rank).toString(), -1).toInt();
    if (bpoints != -1){
        q.prepare("UPDATE Rating SET bonus=(SELECT bonus FROM Rating WHERE nick=:nick)+"+QVariant(bpoints).toString()+" WHERE nick=:nick");
        q.bindValue(":nick", nick);
         if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
syncPoints(nick);
    }

}
}
    }
    stg.setValue("stored", true);
stg.endGroup();
stg.sync();
}
开发者ID:pashazz,项目名称:rksmanager,代码行数:72,代码来源:leaguetrn.cpp

示例15: setupLayout


//.........这里部分代码省略.........
    // set up taxa tab
    taxaModel = new QSqlTableModel(this);
    taxaModel->setTable("taxa");
    if (!tableFilter.isEmpty())
        taxaModel->setFilter(tableFilter);
    taxaModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    taxaModel->select();

    taxaTable = new QTableView(this);
    taxaTable->setModel(taxaModel);
    taxaTable->resizeColumnsToContents();
    taxaTable->sortByColumn(1,Qt::AscendingOrder);
    taxaTable->setSortingEnabled(true);

    // set up organisms tab
    organismsModel = new QSqlTableModel(this);
    organismsModel->setTable("organisms");
    if (!tableFilter.isEmpty())
        organismsModel->setFilter(tableFilter);
    organismsModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    organismsModel->select();

    organismsTable = new QTableView(this);
    organismsTable->setModel(organismsModel);
    organismsTable->resizeColumnsToContents();
    organismsTable->sortByColumn(0,Qt::AscendingOrder);
    organismsTable->setSortingEnabled(true);

    // set up sensu tab
    sensuModel = new QSqlTableModel(this);
    sensuModel->setTable("sensu");
    if (!tableFilter.isEmpty())
        sensuModel->setFilter(tableFilter);
    sensuModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    sensuModel->select();

    sensuTable = new QTableView(this);
    sensuTable->setModel(sensuModel);
    sensuTable->resizeColumnsToContents();
    sensuTable->sortByColumn(0,Qt::AscendingOrder);
    sensuTable->setSortingEnabled(true);

    tabWidget = new QTabWidget(this);
    tabWidget->addTab(agentsTable,"Agents");
    tabWidget->addTab(determinationsTable,"Determinations");
    tabWidget->addTab(imagesTable,"Images");
    tabWidget->addTab(taxaTable,"Names");
    tabWidget->addTab(organismsTable,"Organisms");
    tabWidget->addTab(sensuTable,"Sensu");

    submitButton = new QPushButton(tr("&Save changes"));
    submitButton->setDefault(true);
    refreshButton = new QPushButton(tr("&Revert unsaved changes\nand refresh database"));
    deleteButton = new QPushButton(tr("&Delete selected rows"));
    quitButton = new QPushButton(tr("&Close"));

    buttonBox = new QDialogButtonBox(Qt::Vertical);
    buttonBox->addButton(submitButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(deleteButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(refreshButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(quitButton, QDialogButtonBox::ActionRole);

    connect(submitButton, SIGNAL(clicked()), this, SLOT(submit())); // this needs to save (submit) all changes from all tables
    connect(refreshButton, SIGNAL(clicked()), this, SLOT(refreshAll())); // this needs to refresh all tables to their current database values
    connect(deleteButton, SIGNAL(clicked()), this, SLOT(removeSelectedRows())); // this needs to remove selected rows ONLY from current tab
    connect(quitButton, SIGNAL(clicked()), this, SLOT(confirmClose()));

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(tabWidget);
    mainLayout->addWidget(buttonBox);
    setLayout(mainLayout);

    setWindowTitle("Table view");

    QSqlDatabase db = QSqlDatabase::database();
    db.transaction();

    QSqlQuery qry;
    qry.prepare("SELECT value FROM settings WHERE setting = (?)");
    qry.addBindValue("view.table.location");
    qry.exec();
    if (qry.next())
        restoreGeometry(qry.value(0).toByteArray());

    bool wasMaximized = false;
    qry.prepare("SELECT value FROM settings WHERE setting = (?)");
    qry.addBindValue("view.table.fullscreen");
    qry.exec();
    if (qry.next())
        wasMaximized = qry.value(0).toBool();

    if (!db.commit())
    {
        qDebug() << "Problem committing changes to database in TableEditor::setupLayout()";
        db.rollback();
    }

    if (wasMaximized)
        this->showMaximized();
}
开发者ID:kopolzin,项目名称:bioimages-collection-manager,代码行数:101,代码来源:tableeditor.cpp


注:本文中的QSqlQuery::prepare方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。