Example #1
0
// englisch ??????????????????? !!!!!!!!!!!!!!!!!!!!!!!!
// ---------------------------------------------------------------------------
// ReferenzListe mit Spalten_Namen, UserFeldNamen und ADIf_referenzNamen laden
// ( 4_dimensionales Arryfeld ) zur Aufnahme des Datensatzes
// ---------------------------------------------------------------------------
void wadif::loadRefList()
{
    QSqlQuery query;
    qy = "SELECT dbfield,refnam,adifnam FROM refnamen WHERE type = '2' ORDER BY idn";
    query.exec(qy);
    openRefListQso(query.size());
    
    i = 0;
    while(query.next()) {                                   // Datensatz erzeugen
       n = 0;                                                        // Index_Felder
       adh[i].pos = i;                                               // index_Nr
       strcpy(adh[i].field,query.value(n++).toString().toAscii());   // dbSpalten_Namen
       strcpy(adh[i].refnam,query.value(n++).toString().toAscii());  // User_Name
       strcpy(adh[i].adifnam,query.value(n++).toString().toAscii()); // ADIF_Name
       strcpy(adh[i].value,"");                            // Datensatz_Feld_variable
       i++;
    }
    
 // englich ????????????? !!!!!!!!!!!!!!!!!!!
     // funqsl Tabelle
    qy = "SELECT dbfield,refnam,adifnam FROM refnamen WHERE type='3' OR type ='4' ORDER BY idn";
    query.exec(qy);
    openRefListQsl(query.size());
    i = 0;
    while(query.next()) {                                    // Datensatz erzeugen
       n = 0;                                                         // Index_Felder
       adhq[i].pos = i;                                               // index_Nr
       strcpy(adhq[i].field,query.value(n++).toString().toAscii());   // dbSpalten_Namen
       strcpy(adhq[i].refnam,query.value(n++).toString().toAscii());  // User_Name
       strcpy(adhq[i].adifnam,query.value(n++).toString().toAscii()); // ADIF_Name
       strcpy(adhq[i].value,"");                             // Datensatz_Feld_variable
       i++;
    }
}
Example #2
0
/**
 * @paragraph This method loads an account saved in the local database
 * @brief ServerPanel::LoadLocalAccount
 * @param SpLocalAccount slaAccount
 * @return bool
 */
bool ServerPanel::LoadLocalAccount(SpLocalAccount slaAccount) {
    // Check for a username and password
    if (!slaAccount.getProperty("sUsername").toString().isEmpty() && !slaAccount.getProperty("sPassword").toString().isEmpty()) {
        // Grab the QSqlQuery object
        QSqlQuery qsqLocalAccount = slaAccount.toQuery(this->mDbc, this->mConfig->value("sqlQueries/selectLocalAccountByUsernameAndPassword").toString());
        // Try to execute the query
        if (!qsqLocalAccount.exec()) {
            // Dispatch a message
            this->DispatchMessageBox(qsqLocalAccount.lastError().text(), Error);
            // We're done
            return false;
        }
        // Check for results
        if (!qsqLocalAccount.size()) {
            // We're done
            return false;
        }
        // Loop through the results
        while (qsqLocalAccount.next()) {
            // Set the account object
            slaAccount = SpLocalAccount(qsqLocalAccount.record());
        }
        // Set the account into the system
        this->mCurrentAccount = slaAccount;
        // We're done
        return true;
    }
    // Check for a server address
    if (!slaAccount.getProperty("sAddress").toString().isEmpty()) {
        // Grab the QSqlQuery object
        QSqlQuery qsqAccount = slaAccount.toQuery(this->mDbc, this->mConfig->value("sqlQueries/selectLocalServerAccount").toString());
        // Try to execute the query
        if (!qsqAccount.exec()) {
            // Dispatch a message
            this->DispatchMessageBox(qsqAccount.lastError().text(), Error);
            // We're done
            return false;
        }
        // Check for results
        if (!qsqAccount.size()) {
            // We're done
            return false;
        }
        // Loop through the results
        while (qsqAccount.next()) {
            // Populate the structure
            slaAccount = SpLocalAccount(qsqAccount.record());
        }
        // Set the current account
        this->mCurrentAccount = slaAccount;
        // We're done
        return true;
    }
    // Dispatch a message
    this->DispatchMessageBox("No account identifier found.", Error);
    // We're done
    return false;
}
Example #3
0
/**
 * @paragraph This method loads a saved server from the local database
 * @brief ServerPanel::LoadLocalServer
 * @param SpLocalServer slsServer
 * @return bool
 */
bool ServerPanel::LoadLocalServer(SpLocalServer slsServer) {
    // Are we loading by id
    if (slsServer.getProperty("iServerId").toInt() > 0) {
        // Grab the QSqlQuery object
        QSqlQuery qsqLocalServer = slsServer.toQuery(this->mDbc, this->mConfig->value("sqlQueries/selectLocalServerByServerId").toString());
        // Try to execute the query
        if (!qsqLocalServer.exec()) {
            // Dispatch a message
            this->DispatchMessageBox(qsqLocalServer.lastError().text(), Error);
            // We're done
            return false;
        }
        // Check for results
        if (!qsqLocalServer.size()) {
            // We're done
            return false;
        }
        // Loop through the results
        while (qsqLocalServer.next()) {
            // Set the server object
            slsServer = SpLocalServer(qsqLocalServer.record());
        }
        // Set the server into the system
        this->mCurrentServer = slsServer;
        // We're done
        return true;
    }
    // Are we loading by server address
    if (!slsServer.getProperty("sAddress").toString().isEmpty()) {
        // Grab the QSqlQuery object
        QSqlQuery qsqLocalServer = slsServer.toQuery(this->mDbc, this->mConfig->value("sqlQueries/selectLocalServerByServerAddress").toString());
        // Try to execute the query
        if (!qsqLocalServer.exec()) {
            // We're done
            return false;
        }
        // Check for results
        if (!qsqLocalServer.size()) {
            // We're done
            return false;
        }
        // Loop through the results
        while (qsqLocalServer.next()) {
            // Populate the structure
            slsServer = SpLocalServer(qsqLocalServer.record());
        }
        // Set the server into the system
        this->mCurrentServer = slsServer;
        // We're done
        return true;
    }
    // Dispatch a message
    this->DispatchMessageBox("No server identifier was found.  Please check for a valid server ID or server address and try again.", Error);
    // We're done
    return false;
}
/* SQL without C++:
SELECT id, last, first, full_name, active
FROM prescribers
WHERE active = 1
ORDER BY last, first;

SELECT id, last, first, initials, active
FROM pharmacists
WHERE active = 1
ORDER BY last, first;
*/
bool Prescription_01::initCustom()
{
	QSqlQuery model;				// Contains the query
	AlertInterface alert;
	PrescriberRecord *presTemp;
	PharmacistRecord *pharmTemp;
	int i;							// Increment var

	model.prepare("SELECT id, last, first, full_name, active "
				  "FROM prescribers "
				  "WHERE active = 1 "
				  "ORDER BY last, first;");

	if (!alert.attemptQuery(&model)) {
		return false;
	}
	for (i = 0; i < model.size(); i++) {
		model.next();
		presTemp = new PrescriberRecord;
		presTemp->setId(model.value(0).toInt());
		presTemp->setLast(model.value(1).toString());
		presTemp->setFirst(model.value(2).toString());
		presTemp->setFull_name(model.value(3).toString());
		presTemp->setActive(model.value(4).toBool());
		prescribers.append(presTemp);
	}

	model.prepare("SELECT id, last, first, initials, active "
				  "FROM pharmacists "
				  "WHERE active = 1 "
				  "ORDER BY last, first;");

	if (!alert.attemptQuery(&model)) {
		deleteLists();
		return false;
	}
	for (i = 0; i < model.size(); i++) {
		model.next();
		pharmTemp = new PharmacistRecord;
		pharmTemp->setId(model.value(0).toInt());
		pharmTemp->setLast(model.value(1).toString());
		pharmTemp->setFirst(model.value(2).toString());
		pharmTemp->setInitials(model.value(3).toString());
		pharmTemp->setActive(model.value(4).toBool());
		pharmacists.append(pharmTemp);
	}

	setupComboBoxes();

	return true;
}
Example #5
0
int MainWindow::fillSensorRelated()
{
    QString seqQuery;
    QSqlQuery query;

    seqQuery  = "select distinct name from ActionRules where ruleActionText like '%";
    seqQuery += "::" + ui->sensorComboBox->currentText().section("::",0,0) + "::%' and experimentalLocationId =" + experimentLocation + " order by name";

    qDebug()<<seqQuery;

    query = seqQuery;

    qDebug()<<seqQuery;

    ui->sensorListWidget->clear();

    query.exec();

    while(query.next())
   {
      ui->sensorListWidget->addItem(query.value(0).toString());
    }

    return query.size();


}
Example #6
0
int Category::find()
{
//  qDebug() << "find category";
  QString query = QString("SELECT id, priceID FROM categories WHERE "
                          "teamID = %1 AND techID = %2 AND typeID = %3 AND homeID = %4 AND line = %5;")
      .arg(teamID).arg(techID).arg(typeID).arg(homeID).arg(line);

//  qDebug() << query;

  QSqlQuery *q = new QSqlQuery(query, App::theApp()->db());

  q->exec();

  if (q->size() == 0) { // нет этой категории, создаем категорию...
    if (!create()) return -1;
    // Создали, находим (рекурсивно)
    return find();
  }

  q->first();

  int id = q->value("id").toInt();
  int priceID = q->value("priceID").toInt();

  price = Price(priceID);
//  qDebug() << "find category. ID = " << id << " priceID = " << priceID;
  return id;
}
Example #7
0
Patient *SearchPatient(QString id)
{
    if(id=="")
        return NULL;
    QSqlQuery query;
    QString sql="select * from TPatient where Id='"+id+"'";
    bool boo=query.exec(sql);
    if(!boo || query.size()==0)
        return NULL;
    query.first();
    Patient *p=new Patient();
    p->setNom(query.value(1).toString());
    p->setPrenom(query.value(2).toString());
    p->setAdresse(query.value(3).toString());
    p->setVille(query.value(4).toString());
    p->setCP(query.value(5).toInt());
    p->setCommentaire(query.value(6).toString());
    p->setTelephone(query.value(7).toString());
    p->setDateDebut(query.value(8).toDate());
    p->setDuree(query.value(9).toInt());
    p->setPriorite(query.value(10).toInt());

    query.exec("select IdRessource from TConsult where IdPatient="+id);
    while(query.next())
    {
        p->vIdRessource.push_back(query.value(0).toInt());
    }
    return p;
}
Example #8
0
bool Auth::userLogin ( const QString &username , const QString &password )
{
    if ( m_AuthType == NONE && !m_needAuth )
    {
        qDebug ( "userLogin::Try to login with NONE ? Please Fix this." );
        return m_isAuth = true;
    }
    /*if ( m_AuthType == HASHED){
            qDebug("userLogin::HASHED Auth not implemented yet!");
            return m_isAuth = true;
    }*/
    QSqlDatabase db = QSqlDatabase::database ( m_db );

    QSqlQuery query = db.exec ( QString ( "SELECT * from Users where Username = '%1' and Password = password('%2') and Enabled = 1" ).arg ( username ).arg ( password ) );
    query.next();
    if ( query.size() != 1 )
        return m_isAuth = false;

    /* OK */
    m_userName = username;
    if ( m_AuthType == HASHED ){
	  int passField = query.record().indexOf("Password");
	  m_hashPassword = query.value( passField ).toString();
    }
    
    m_password = password;
    saveSettings();
    return m_isAuth = true;
}
census * DatabaseHandler::getCensusData(QString objId) {
    qDebug() << "Getting object specific query for ID: " << objId;
    QString qstr = "SELECT tp, name, confidence, beh, age, gen, dir, rem, censor, imgqual FROM census WHERE rcns_id=" + objId +
            " AND usr!='" + config->user() + "' AND censor=1";
    qDebug() << qstr;
    // if there is already an entry in census db-table,
    // initialize census structure with these values
    QSqlQuery * query = new QSqlQuery(qstr);
    if (query->size() != 1) {
        delete query;
        return 0;
    }
    census * obj = new census;
    if (query->next()) {
        obj->type = query->value(0).toString();
        obj->name = query->value(1).toString();
        obj->confidence = query->value(2).toInt();
        obj->behavior = query->value(3).toString();
        obj->age = query->value(4).toString();
        obj->gender = query->value(5).toString();
        obj->direction = query->value(6).toInt();
        obj->remarks = query->value(7).toString();
        obj->censor = query->value(8).toInt();
        obj->imageQuality = query->value(9).toInt();
    }
    delete query;
    return obj;
}
Example #10
0
void FrmCell::filterModel4Combo()
{
    QString strQuery =
            "select     fr_gls2als.id_abstract_landingsite as ls, ref_minor_strata.id_gls, fr_gls2als.id_gls as expr1"
            " from         ref_minor_strata inner join"
            "                      fr_time on ref_minor_strata.id_frame_time = fr_time.id inner join"
            "                      fr_frame on fr_time.id_frame = fr_frame.id inner join"
            "                      fr_sub_frame on fr_frame.id = fr_sub_frame.id_frame inner join"
            "                      fr_gls2als on fr_sub_frame.id = fr_gls2als.id_sub_frame and ref_minor_strata.id_gls = fr_gls2als.id_gls"
            " where     (ref_minor_strata.id = :id)"
;

    QSqlQuery query;
    query.prepare(strQuery);
    query.bindValue(0,m_sample->minorStrataId);
    if (!query.exec()){
        emit showError(tr("Could not obtain filter for Landing Sites!"));
        return;
    }

    Q_ASSERT_X(query.size()>=1, "Cell", QString(QString("Selection of a GLS without landing sites!") + m_sample->print()).toUtf8().constData());

    QString strFilter("");
     while (query.next()) {
        strFilter.append("ID=" + query.value(0).toString());
        strFilter.append(" OR ");
     }
     if (!strFilter.isEmpty())
         strFilter=strFilter.remove(strFilter.size()-QString(" OR ").length(),QString(" OR ").length());

    tSampCell->relationModel(2)->setFilter(strFilter);
    //first we set the relation; then we create a mapper and assign the (amended) model to the mapper;
    initMapper1();
}
Example #11
0
void TestAnalysisDao::testAddAnalysis(){
    //Add network and archive
    addTestArchive1();

    //Create analysis info with analysis information
    AnalysisInfo analysisInfo(0, testNetID, testArchive1ID, QDateTime::fromTime_t(1234321), "Test analysis description 1", QHash<QString, double>(), 1);

    try{
		//Invoke method that is being tested
		AnalysisDao analysisDao(analysisDBInfo);
		analysisDao.addAnalysis(analysisInfo);

		//Check that analysis has been added
		QSqlQuery query = getAnalysisQuery("SELECT NetworkID, ArchiveID, StartTime, Description, AnalysisTypeID FROM Analyses");
		executeQuery(query);

		//Should only be one row
		QCOMPARE(query.size(), 1);
		query.next();

		//Check details of archive
		QVERIFY( analysisInfo.getID() != 0);
		QCOMPARE(query.value(0).toUInt(), testNetID);
		QCOMPARE(query.value(1).toUInt(), testArchive1ID);
		QCOMPARE(query.value(2).toUInt(), (unsigned int)1234321);
		QCOMPARE(query.value(3).toString(), QString("Test analysis description 1"));
		QCOMPARE(query.value(4).toUInt(), (unsigned int)1);
    }
    catch(SpikeStreamException& ex){
		QFAIL(ex.getMessage().toAscii());
    }

}
Example #12
0
bool otros::completar()
{
    QSqlQuery query;
    query.prepare("SELECT p.idProducto,p.accesorios,p.observaciones FROM Producto p,Otros o WHERE p.idProducto=o.Producto_idProducto AND p.codigo=? AND p.descripcion=? AND p.precioCompra=? AND p.precioVenta=? AND p.precioDescuento=? AND p.stock=? AND p.Estado_idEstado=? AND p.Marca_idMarca=? AND o.Color_idColor=? AND o.Talla_idTalla=? AND o.Calidad_idCalidad=? AND o.TipoOtros_idTipoOtros=? AND o.Genero_idGenero=?");//falta seleccionar colaborador
    query.bindValue(0,codigo);
    query.bindValue(1,descripcion);
    query.bindValue(2,precioCompra);
    query.bindValue(3,precioVenta);
    query.bindValue(4,precioDescuento);
    query.bindValue(5,stock);
    query.bindValue(6,pEstado.getIdEstado());
    query.bindValue(7,pMarca.getIdMarca());
    query.bindValue(8,pColor.getIdColor());
    query.bindValue(9,pTalla.getIdTalla());
    query.bindValue(10,pCalidad.getIdCalidad());
    query.bindValue(11,pTipoOtros.getIdTipoOtros());
    query.bindValue(12,pGenero.getIdgenero());
    if(query.exec())
    {
        if(query.size()!=0)
        {
            query.first();
            idProducto=query.value(0).toString();
            accesorios=query.value(1).toString();
            observaciones=query.value(2).toString();
            return true;
        }
        else
            return false;
    }
    else
        return false;
}
QString DatabaseController::makeQueryResultString(const QSqlQuery& query, int iNbRowsSelected)
{
	QString szResultString;
	QTime time;

	int iNbRow = 0;
	if(query.isSelect()){
		iNbRow = query.size();
		if(iNbRow == -1){
			iNbRow = iNbRowsSelected;
		}
	} else {
		iNbRow = query.numRowsAffected();
	}

	// Write the time
	szResultString += time.currentTime().toString()+" => ";
	// Write sql error
	if(query.lastError().isValid()){
		szResultString += "Query executed with error(s) (" + query.lastError().text() + "): \n";
	}else{
		szResultString += "Query executed successfully: ";
	}
	// Write number of rows
	szResultString += QString::number(iNbRow)+" row(s) selected/affected\n";
	// Write query
	if(!query.lastQuery().isEmpty()){
		szResultString += query.lastQuery() + "\n";
	}
	szResultString += "\n";

	return szResultString;
}
Example #14
0
QSqlQuery MainData::makeQuery(QString q_str,bool& made,bool silent)
{
    QSqlQuery query;
    try
    {
        query.exec(q_str);
        if(query.isActive())
        {

             if(query.size()==0) throw "Неверный логин/пароль";
             if(!query.first()) throw "Ошибка при запросе данных из БД";
             made=true;
             return query;
        }
        else
            throw "Не могу выполнить запрос к БД";
    }
    catch(QString message)
    {

        if(!silent) MessageHandler::showMessage(MessageHandler::Error,message,0);
        made=false;
        query.clear();
    }
    catch(...)
    {
        if(!silent) MessageHandler::showMessage(MessageHandler::Error,"Ошибка при работе с БД\n"+q_str,0);
        made=false;
        query.clear();
    }


 }
Example #15
0
// ---------------------------------------------
// Neuen AWARD_Type anlegen
// ---------------------------------------------
void confMode::NewAwdValues()
{
      QSqlQuery query;
      if(NameTypeLineEdit->text().count() == 0) {
        QMessageBox::information( this,
        tr("INFO"),
        tr("\n\nKeinen leeren AWD Type !"),
        QMessageBox::Ok);
        return;
      }
      
      qy = "SELECT aset FROM wawdlist WHERE atype='"+NameTypeLineEdit->text()+"'";
      query.exec(qy);
      if(query.size() != 0) {                                         // schon vorhanden   
           QMessageBox::information(this,
           tr("Information"),
           tr("\n\nAWD Type ist schon vorhanden"),
           QMessageBox::Ok);
          return;
      }
      if(AwdSetLineEdit->text().count() == 0)
         AwdSetLineEdit->setText("0");
      qy = "INSERT INTO wawdlist VALUES(0,'"+AwdSetLineEdit->text();  // aset : sortNo
      qy += "','"+NameTypeLineEdit->text();                           // atype : Name_Award-Type
      qy += "','APP_QTLOG_"+NameTypeLineEdit->text()+"')";            // Applocation_QtLog + Name-AWtype
      query.exec(qy);
         
      QTreeWidgetItem *item = new QTreeWidgetItem(awdList);
      item->setText(0,AwdSetLineEdit->text());                        // aset
      item->setText(1, NameTypeLineEdit->text());                     // atype
      NewPushButton->hide();
}
Example #16
0
//returns all info associated with the record of specified id
HistoryItem DbManager::getHistoryItem(const int& id) const
{

    QSqlQuery query;
    query.prepare("SELECT * FROM History WHERE id = :id");
    query.bindValue(":id", id);
    if (!query.exec()) { qCritical() << "The getHistoryItemStats select statement couldn't be executed"; }

    qDebug() << query.size();

    HistoryItem historyItem;

    if (query.next())
    {
        historyItem.id = query.value(query.record().indexOf("id")).toInt();
        historyItem.fileName = query.value(query.record().indexOf("fileName")).toString();  //Get the data from the query
        historyItem.dateTime = query.value(query.record().indexOf("dateTime")).toString();
        historyItem.compressionRatio = query.value(query.record().indexOf("compressionRatio")).toDouble();
        historyItem.originalSize = query.value(query.record().indexOf("originalSize")).toDouble();
        historyItem.compressedSize = query.value(query.record().indexOf("compressedSize")).toDouble();
        historyItem.executionTime = query.value(query.record().indexOf("executionTime")).toDouble();
        historyItem.notes = query.value(query.record().indexOf("notes")).toString();
    }

    //checking that there was indeed only one query returned. BTW, query.size() always returns 0
    query.last();
    Q_ASSERT( query.at() + 1 == 1); //how can there be more than one record associated with the unique id?


    return historyItem;
}
ForDelete::ForDelete(QString id, QString tabNameAud, QWidget *parent) :
    QDialog(parent)
{
    tabNameAuditee = tabNameAud;
    indexTemp = id;
    QSettings settings("AO_Batrakov_Inc.", "EmployeeClient");
    tabNameAuditee = settings.value("Table").toString();
    indexTemp = settings.value("Index").toString();

    QVBoxLayout *mainLayout = new QVBoxLayout;
    QSqlQuery query;
    query.exec("select tbl_name from sqlite_master where type = 'table'");//SQLite

    QLabel *newLabel = new QLabel;
    labelLabel = new QLabel;
    QString toOut;
    QPushButton *okButton = new QPushButton("Ok");
    connect(okButton,SIGNAL(clicked()),this,SLOT(close()));

    while(query.next()){
        if(tabNameAuditee != query.value(0).toString()){//имя таблицы
            QSqlQuery queryTable;

            QString table = query.value(0).toString();
            QString tableid = table;
            tableid += "id";
            QString tableName = table;
            tableName += "name";
            QString textQuery = "SELECT ";
            textQuery += tableid;
            textQuery += ", ";
            textQuery += tableName;
            textQuery += " FROM ";
            textQuery += table;
            textQuery += " WHERE ";
            textQuery += tabNameAuditee;
            textQuery += "id = '";
            textQuery += indexTemp;
            textQuery += "';";
            queryTable.exec(textQuery);
            queryTable.next();
            if(queryTable.isActive()){
                toOut = tr("Table ");
                toOut += table;
                toOut += tr(" contains - ");
                toOut += QString::number(queryTable.size());
                toOut += tr(" records.");
                newLabel->setStyleSheet("font: bold; color: red;");
            }else{
                toOut = "No related Tables! Deleting.";
                newLabel->setStyleSheet("font: bold; color: darkblue;");
            }
        }
    }
    newLabel->setText(toOut);
    mainLayout->addWidget(newLabel);
    mainLayout->addWidget(okButton);
    setLayout(mainLayout);
    setWindowTitle(tr("Conditions for removal..."));
}
bool JSQLGameInfoDB::isGameIdExist(JID id)
{
	QSqlQuery query;
	PREPARE( query ,
			"select game_id from gameinfo "
			"where game_id= :gameID" ,
			false );
	
	query.bindValue(":gameID", id);
	
	EXEC( query , false );
	
	if( query.driver()->hasFeature(QSqlDriver::QuerySize) ){
		if(query.size() > 0){
			return true;
		}else{
			return false;
		}
	}else{
		if(query.next()){
			return true;
		}else{
			return false;
		}
	}
}
Example #19
0
std::shared_ptr<Client> ClientController::GetClientById(qint32 clientId)
{
    if(!(UserSingleton::GetInstance().GetPermissions() & PLM::PermissionsFlag::READ_CLIENTS))
    {
        return std::shared_ptr<Client>();
    }

    auto existingClient = m_cache.Lookup(clientId);
    if(existingClient)
    {
        return existingClient;
    }

    QSqlQuery query = GetDb().CreateQuery();
    query.prepare("SELECT * "
        "FROM \"Client\""
        "INNER JOIN \"ContactView\" ON \"Client\".\"ContactId\" = \"ContactView\".\"ContactId\""
        "WHERE \"Client\".\"ClientId\"=:clientId;"
    );
    query.bindValue(":clientId", clientId);
    if(!query.exec())
    {
        return std::shared_ptr<Client>();
    }

    if(!query.size() != 1)
    {
        return std::shared_ptr<Client>();
    }

    query.next();
    auto client = CreateClientFromQuery(query);
    auto sharedPtr = AddClient(std::move(client));
    return sharedPtr;
}
Example #20
0
void dxspot::getLaPrefix(QString callstr)
{
  QString dxcc, lname, cnt, cqz, br, lg;
     QSqlQuery query;                                  
     qy = "SELECT ldxcc,lname,lcn,ituz,cqz,br,lg FROM tpref,tla WHERE pref=la AND spref='"+callstr+"'";
     query.exec(qy);  
     if(query.size() == 1) {                           
       n = 0;
       query.next();
       
       dxcc = query.value(n++).toString();             
       lname = query.value(n++).toString();            
       cnt = query.value(n++).toString();              
       
       s = dxcc+"  - "+lname+"   "+cnt+" /  ";         
       s += "ITU: "+query.value(n++).toString();       
       cqz = "  -  CQz: "+query.value(n++).toString(); 
       s += cqz;
       labelInfo->setText(s); 
       
       br = query.value(n++).toString();               
       lg = query.value(n++).toString();               
       s = distanz.getDisRicht(br,lg);                 
       labelDistanz->setText(s);                       
     }
}
Example #21
0
void LogEngine::checkDBSize()
{
    QString queryString = "SELECT ROWID FROM entries;";
    QSqlQuery query;
    query.exec(queryString);
    int numRows = 0;
    if (m_db.driver()->hasFeature(QSqlDriver::QuerySize)) {
        numRows = query.size();
    } else {
        // this can be very slow
        query.last();
        numRows = query.at() + 1;
    }

    if (numRows >= m_dbMaxSize) {
        // keep only the latest m_dbMaxSize entries
        qCDebug(dcLogEngine) << "Deleting oldest entries and keep only the latest" << m_dbMaxSize << "entries.";
        QString queryDeleteString = QString("DELETE FROM entries WHERE ROWID IN (SELECT ROWID FROM entries ORDER BY timestamp DESC LIMIT -1 OFFSET %1);").arg(QString::number(m_dbMaxSize));
        if (!query.exec(queryDeleteString)) {
            qCWarning(dcLogEngine) << "Error deleting oldest log entries to keep size. Driver error:" << query.lastError().driverText() << "Database error:" << query.lastError().databaseText();
        } else {
            emit logDatabaseUpdated();
        }
    }
}
void outLibDialog::outLib()
{
    QString merchantID = ui->comboBoxMerchant->currentText();
    QString storeID = ui->comboBoxStore->currentText();
    QString sql;
    QString num = ui->spinBox->text();
    QSqlQuery query;
    //更新merchantStore
    if(num.toInt() == ui->spinBox->maximum()){
        sql = "delete from merchantStore where storeNumber = '"+storeID+"' and merchantNumber = '"+merchantID+"';";
    }else{
        sql = "update merchantStore set number = number - "+num+" where storeNumber = '"+storeID+"' and merchantNumber = '"+merchantID+"';";
    }
    //更新store
    sql = sql + "update store set leftCap = leftCap + "+num+" where storeNumber = '"+storeID+"';";
    //更新goodsShelve
    if(!query.exec("select * from goodsshelve where merchantNumber = '"+merchantID+"'")){
        tips("错误","数据库出错");
        return;
    }

    if(query.size()){
        sql = sql + "update goodsShelve set number = number +"+num+" where merchantNumber = '"+merchantID+"';";
    }
    else{
        sql = sql + "insert into goodsShelve values('"+merchantID+"','"+num+"');";
    }
    if(!query.exec(sql)){
        tips("错误","数据库出错");
        return;
    }
    tips("提示","出库成功");
    this->accept();
}
Example #23
0
Category::Category(int id)
{
  ID = id;
  teamID = 0;
  techID = 0;
  typeID = 0;
  homeID = 0;
  line = -1;

  if (ID <= 0) return;

  QString query = QString("SELECT teamID, techID, typeID, homeID, line FROM categories WHERE id=%1;").arg(ID);

  QSqlQuery *q = new QSqlQuery(query, App::theApp()->db());

  q->exec();
  if (q->size() == 0) return; // Категория не найдена, выход
  q->first();

  teamID = q->value("teamID").toInt();
  techID = q->value("techID").toInt();
  typeID = q->value("typeID").toInt();
  homeID = q->value("homeID").toInt();
  line = q->value("line").toInt();
}
Example #24
0
void MainWindow::readAd(int adId)//读取广告
{
    QSqlQuery adQuery;//对广告表单搜索
    if(adQuery.exec("SELECT aditem FROM adtable WHERE id = "+QString().setNum(adId)))
    {
        int adNumRows = 0;//定义搜索返回的行数
        if(db.driver()->hasFeature(QSqlDriver::QuerySize))//判断驱动是否包含QuerySize
        {
            adNumRows = adQuery.size();//将返回的行数赋于fstNumRows
        }
        else
        {
            adQuery.last();//移至最后一行
            adNumRows = adQuery.at()+1;//将返回的行数赋于fstNumRows
            adQuery.seek(-1);//返回第一行
        }
        if(adNumRows>0)//判断是否大于0
        {
            while(adQuery.next())
            {
                this->adView->loadMap(adQuery.value(0).toByteArray());//读取广告
            }
        }
    }
}
Example #25
0
void Price::fillByID()
{
  if (ID <= 0) {
    line = 0;
    first = 0;
    second = 0;
    third = 0;
  }

//  qDebug() << "fill price by ID";
  QString query = QString("SELECT line, first, second, third FROM prices WHERE id=%1;").arg(ID);

//  qDebug() << query;

  QSqlQuery *q = new QSqlQuery(query, App::theApp()->db());

  q->exec();

  if (q->size() == 0) return; // Цена не найдена, выход

  q->first();

  line = q->value("line").toInt();
  first = q->value("first").toInt();
  second = q->value("second").toInt();
  third = q->value("third").toInt();
}
Example #26
0
QString MusicDatabase::getFilename(int id) {

    if (this->connect()) {
        QString sqlQuery = QString("SELECT file_name FROM rebetikosongs.song WHERE rec_id = :id");

        // Execute the query
        QSqlQuery resultSet;
        resultSet.prepare( sqlQuery );
        resultSet.bindValue(":id", id);
        resultSet.exec();

        if (resultSet.size() > 0) {

            QString value;
            if (resultSet.next()) {
                QString normalized = normalizeUrl(resultSet.value(0).toString());
                value = Song::base_filename + normalized;
            }

            // Disconnect from database
            this->disconnect();

            // Return value
            return value;

        }

    }

    return QString("");
}
bool JSQLUserInfoDB::isUserIdExist(JID id){
	QSqlQuery query;
	PREPARE( query ,
			"select * from userinfo "
			"where user_id = :userId" ,
			false );
	
	query.bindValue(":userId", id);
	
	EXEC( query , false );
	
	if( query.driver()->hasFeature(QSqlDriver::QuerySize) ){
		if(query.size() > 0){
			return true;
		}else{
			return false;
		}
	}else{
		if(query.next()){
			return true;
		}else{
			return false;
		}
	}
}
Example #28
0
// load AWD_customs_field_list und im Dialog anzeigen
// --------------------------------------------------
void admin::getCustomsfields()
{
    QString y;
    QSqlQuery query;
    qy = "SELECT id,atype,adiftype FROM wawdlist WHERE aset !='0' ORDER BY id";
    query.exec(qy);
    row = query.size();                     // anzahl aedTypen
    customsTable->setRowCount(row);         // TabellenLänge setzen - col ist schon gesetzt
    row = 0;
    customsTable->setColumnWidth(0,63); 
    customsTable->setColumnWidth(1,160); 
    QBrush brush(QColor(217,207,196)); 
    while(query.next()) {
      z = 0;
      r = 0;
      col = 0;
      i = 0;
      y = query.value(i++).toString();
      QTableWidgetItem *rowItem = new QTableWidgetItem(tr("%1").arg((r++)*(z++))); //idn
      rowItem->setText(y);
      customsTable->setVerticalHeaderItem(row,rowItem);
      QTableWidgetItem *newItem = new QTableWidgetItem(tr("%1").arg((row)*(col)));//dbFeld
      newItem->setText(query.value(i++).toString());
      customsTable->setItem(row,col++,newItem);
      newItem->setBackground(brush);
      newItem = new QTableWidgetItem((tr("%1").arg((row)*(col))));                 // ADIF_name
      newItem->setText(query.value(i).toString());
      customsTable->setItem(row,col++,newItem);
      row++;
    }
}
Example #29
0
bool alerta::completar()
{
    QSqlQuery query;
    query.prepare("SELECT idAlerta,fechaInicio,fechaFin,color FROM Alerta WHERE hora = ? AND descripcion = ?");
    query.bindValue(0,hora);
    query.bindValue(1,descripcion);

    if(query.exec())
    {
        if(query.size()!=0)
        {
            query.first();
            idAlerta=query.value(0).toString();
            fechainicio=query.value(1).toString();
            fechafin=query.value(2).toString();
            color=query.value(3).toString();

            return true;
        }
        else
            return false;
    }
    else
        return false;
}
Example #30
0
void Client::login(const QString& login, const QString& mdp)
{
    QSqlQuery query;
    query.prepare("SELECT id FROM user WHERE pseudo = :login AND mdp = :mdp");
    query.bindValue(":login", login);
    query.bindValue(":mdp", mdp);
    if(!query.exec())
    {
        qDebug() << "impossible d'executer la requete de login" << query.lastError().text();
        send(Message::LoginFailure("Erreur serveur"));
        return;
    }

    if(query.size() != 1)
    {
        send(Message::LoginFailure("Informations de login incorrectes"));
        return;
    }

    setPseudo(login);
    query.first();
    setId(query.value(0).toULongLong());
    setPlayer(DataAccessor::getPlayer(id()));
    send(Message::LoginSuccess(id()));
}