示例#1
1
void Database::deactivateUser(QString &userName)
{
    QSqlTableModel model;
    model.setTable("user");
    model.select();

    for (int i=0; i<model.rowCount(); ++i)
    {
        QSqlRecord record = model.record(i);
        if (record.value("name").toString()==userName)
        {
            record.setValue("isActive", false);
            model.setRecord(i, record);
            model.submitAll();
            break;
        }
    }
}
示例#2
0
void CDeleteAclTask::sendCMD(int groupId)
{
	QSqlTableModel model;
	QString filter1;
	SACL* psacl;
	char* pSendBuff;
	int len,len1;
	int ruleCount;

	model.setTable("aclrules");
	filter1 = QString("groupid=%1").arg(groupId);
	model.setFilter(filter1);
	model.select();

	ruleCount=model.rowCount();

	if (ruleCount==0)
	{
		//QMessageBox::information(this,"information", G2U(""));
		return;
	}

	psacl=new SACL[ruleCount];

	for (int i=0;i<model.rowCount();++i)
	{
		QSqlRecord record=model.record(i);
		psacl[i].cmdType=ACL_DELETE;             
		psacl[i].id=record.value("id").toInt();
	}

	len1=sizeof(SACL);
	len=ruleCount*len1;
	pSendBuff=new char[len];

	for (int i=0;i!=ruleCount;++i)
	{
		memcpy_s(pSendBuff+len1*i, len, (char*)&(psacl[i]), len1 );
	}

	boost::asio::io_service ios;
	CSocketClientSyn socketClientSyn(ios); 
	socketClientSyn.startConnection();
	socketClientSyn.sendData(pSendBuff,len);

	char* pRecvBuff=new char[len];
	socketClientSyn.recvData(pRecvBuff,len);
	socketClientSyn.closeConnection();

	for (int i=0;i!=ruleCount;++i)
	{
		memcpy_s(&psacl[i],len1,pRecvBuff+len1*i,len1);
		updateRules(psacl[i].id,psacl[i].cmdType);
	}
	delete [] psacl;
	delete [] pRecvBuff;
	delete [] pSendBuff;
}
示例#3
0
void MainWindow::importData()
{
	int exam_id;
	QString dataFileName = QFileDialog::getOpenFileName(this,tr("Import Data From a CSV File"),QDir::homePath(),tr("CSV File (*.csv)"));
	if(dataFileName.isEmpty())
		return;
	QFile dataFile(dataFileName);
	if(!dataFile.open(QIODevice::ReadOnly))
	{
		QMessageBox::critical(this,tr("Open File Failed"),tr("Cannot open selected file"));;
		return;
	}

	QSqlTableModel* student = m_scoreView->studentListModel();
	QSqlTableModel* exam = m_scoreView->examListModel();
	QSqlRelationalTableModel* score = m_scoreView->scoreListModel();

	QFileInfo tmp(dataFileName);
	QString exam_name = tmp.baseName();
	exam->setFilter(QString("name = \'%1\'").arg(exam_name));
	if(exam->rowCount() == 1)
	{
		QSqlRecord rq = exam->record(0);
		exam_id = rq.value("id").toInt();
	}
	else
	{
		exam->insertRow(0);
		exam->setData(exam->index(0,Global::Exam_Name),exam_name);
		exam->submitAll();
		exam->setFilter(QString("name = \'%1\'").arg(exam_name));
		QSqlRecord rq = exam->record(0);
		exam_id = rq.value("id").toInt();
	}

	QHash<QString,int> studentMap;
	for(int row = 0;row < student->rowCount();++row)
		studentMap.insert(student->data(student->index(row,1)).toString(),student->data(student->index(row,0)).toInt());

	QTextStream in(&dataFile);
	QString record = in.readLine();
	QStringList candidate_seps;
	candidate_seps << ";" << "," << "\t" << " ";
	QString real_sep;
	bool is_legal = false;
	QStringList cols;
	foreach(real_sep, candidate_seps)
	{
		cols = record.split(real_sep);
		if(cols.size() == 11)
		{
			is_legal = true;
			break;
		}
	}
示例#4
0
void Database::saveUnits(QString userName, QList<Unit> units)
{
    QSqlTableModel model;
    model.setTable("user");
    model.select();
    QString saveName;

    for (int i=0; i<model.rowCount(); ++i)
    {
        QSqlRecord record = model.record(i);
        if (record.value("name").toString()==userName)
        {
            saveName=record.value("id").toString();
            break;
        }
    }
    saveName.prepend("save");



    model.setTable(saveName);
    int row=0, line=0;
    model.select();
    model.removeRows(row, model.rowCount());
    model.submitAll();

    while(line<units.size())
    {
        model.insertRows(row,1);
        model.setData(model.index(row,0), line+1);
        model.setData(model.index(row,1), units[line].imageFileName);
        model.setData(model.index(row,2), units[line].faceLeft);
        model.setData(model.index(row,3), units[line].vLocation);
        model.setData(model.index(row,4), units[line].hLocation);
        model.setData(model.index(row,5), units[line].hitPoints);
        model.setData(model.index(row,6), units[line].totalHitPoints);
        model.setData(model.index(row,7), units[line].actionTime);
        model.setData(model.index(row,8), units[line].actionRate);
        model.setData(model.index(row,9), units[line].movementRange);
        model.setData(model.index(row,10), units[line].attackRange);
        model.setData(model.index(row,11), units[line].attackPower);
        model.setData(model.index(row,12), units[line].status);
        model.setData(model.index(row,13), units[line].maskFileName);
        model.setData(model.index(row,14), units[line].team);
        model.setData(model.index(row,15), units[line].unitWorth);
        model.submitAll();
        line++;

    }

}
void CollectionTreeWidget::showChildrenOf(QModelIndex index) {
    CollectionTreeWidgetItem *item = (CollectionTreeWidgetItem*)itemFromIndex(index);

    // If the item pressed was an artist, add albums
    if (item->getNodeLevel() == LevelArtist) {
        QString artist = item->text(0).toUtf8();

        // Looks for artist id
        QString artistId = QString::number(item->getId());

        // Looks for artist albums
        QSqlTableModel *albumModel = service->albumModel();
        albumModel->setFilter("id_artist = " + artistId);
        albumModel->select();

        while (albumModel->canFetchMore()) albumModel->fetchMore();
        int total = albumModel->rowCount();

        for (int i = 0; i < total; i++) {
            QString album = albumModel->record(i).value(albumModel->fieldIndex("title")).toString();
            unsigned int id = albumModel->record(i).value(albumModel->fieldIndex("id")).toInt();
            addAlbum(artist, album, id);
        }

        delete albumModel;
    }
    // If the item pressed was an album, add songs
    else if (item->getNodeLevel() == LevelAlbum) {
        QString albumId = QString::number(item->getId());

        QSqlTableModel *musicModel = service->musicModel();
        musicModel->setFilter("id_album = " + albumId);
        musicModel->setSort(musicModel->fieldIndex("track_number"), Qt::AscendingOrder);
        musicModel->select();

        while (musicModel->canFetchMore()) musicModel->fetchMore();
        int total = musicModel->rowCount();

        for (int i = 0; i < total; i++) {
            QString path = musicModel->record(i).value(musicModel->fieldIndex("path")).toString();
            unsigned int id = musicModel->record(i).value(musicModel->fieldIndex("id")).toInt();

            Music *music = new Music(QUrl(path));
            addMusic(music, id);
            delete music;
        }
    }

    expand(index);
}
示例#6
0
QList<Unit> Database::loadUnits(QString userName)
{
    QSqlTableModel model;
    model.setTable("user");
    model.select();
    QString loadName;

    for (int i=0; i<model.rowCount(); ++i)
    {
        QSqlRecord record = model.record(i);
        if (record.value("name").toString()==userName)
        {
            loadName=record.value("id").toString();
            break;
        }
    }
    loadName.prepend("save");

    Unit units;
    QList<Unit> u;

    model.setTable(loadName);
    model.select();

    for (int i=0; i<model.rowCount(); ++i)
    {
        QSqlRecord record = model.record(i);
        units.imageFileName = record.value("imageFileName").toString();
        units.faceLeft = record.value("faceLeft").toInt();
        units.vLocation = record.value("vLocation").toInt();
        units.hLocation = record.value("hLocation").toInt();
        units.hitPoints = record.value("hitPoints").toInt();
        units.totalHitPoints = record.value("totalHitPoints").toInt();
        units.actionTime = record.value("actionTime").toFloat();
        units.actionRate = record.value("actionRate").toInt();
        units.movementRange = record.value("movementRange").toInt();
        units.attackPower = record.value("attackPower").toInt();
        units.attackRange =record.value("attackRange").toInt();
        units.status = record.value("status").toInt();
        units.maskFileName = record.value("maskFileName").toString();
        units.team = record.value("team").toInt();
        units.unitWorth = record.value("unitWorth").toInt();
        units.image.load(record.value("imageFileName").toString());
        units.mask_image.load(record.value("maskFileName").toString());

        u<<units;
    }
    return u;
}
示例#7
0
void QgsBookmarks::addClicked()
{
    QSqlTableModel *model = qobject_cast<QSqlTableModel *>( lstBookmarks->model() );
    Q_ASSERT( model );

    QgsMapCanvas *canvas = QgisApp::instance()->mapCanvas();
    Q_ASSERT( canvas );

    QSqlQuery query( "INSERT INTO tbl_bookmarks(bookmark_id,name,project_name,xmin,ymin,xmax,ymax,projection_srid)"
                     "  VALUES (NULL,:name,:project_name,:xmin,:xmax,:ymin,:ymax,:projection_srid)",
                     model->database() );

    QString projStr( "" );
    if ( QgsProject::instance() )
    {
        if ( !QgsProject::instance()->title().isEmpty() )
        {
            projStr = QgsProject::instance()->title();
        }
        else if ( !QgsProject::instance()->fileName().isEmpty() )
        {
            QFileInfo fi( QgsProject::instance()->fileName() );
            projStr = fi.exists() ? fi.fileName() : "";
        }
    }

    query.bindValue( ":name", tr( "New bookmark" ) );
    query.bindValue( ":project_name", projStr );
    query.bindValue( ":xmin", canvas->extent().xMinimum() );
    query.bindValue( ":ymin", canvas->extent().yMinimum() );
    query.bindValue( ":xmax", canvas->extent().xMaximum() );
    query.bindValue( ":ymax", canvas->extent().yMaximum() );
    query.bindValue( ":projection_srid", QVariant::fromValue( canvas->mapSettings().destinationCrs().srsid() ) );
    if ( query.exec() )
    {
        model->setSort( 0, Qt::AscendingOrder );
        model->select();
        lstBookmarks->scrollToBottom();
        lstBookmarks->setCurrentIndex( model->index( model->rowCount() - 1, 1 ) );
        lstBookmarks->edit( model->index( model->rowCount() - 1, 1 ) );
    }
    else
    {
        QMessageBox::warning( this, tr( "Error" ), tr( "Unable to create the bookmark.\nDriver:%1\nDatabase:%2" )
                              .arg( query.lastError().driverText() )
                              .arg( query.lastError().databaseText() ) );
    }
}
bool DatabaseHandler::writeCensus(census * obj) {
    qDebug() << "Writing object data to database.";
    QSqlTableModel table;
    table.setTable("census");
    table.setFilter("rcns_id=" + QString::number(obj->id) + " AND usr='******'");
    table.select();
    // get record structure from db
    QSqlRecord record(table.record());
    // initialize record with census-structure values
    setRecordTable(&record, obj);

    // insert or update records in db
    if (table.rowCount() == 0) { //INSERT
        qDebug() << "Insert!";
        // remove first entry of record
        // auto increment of id is handled by postgres
        record.remove(0);
        bool done = table.insertRecord(-1,record);
        qDebug() << table.lastError();
        return done;
    } else { //UPDATE
        qDebug() << "Update!";
        record.setValue("fcns_id",table.record(0).value(0).toInt());
        bool check = true;
        check = check && table.setRecord(0, record);
        check = check && table.submitAll();
        qDebug() << table.lastError();
        return check;
    }
    return true;
}
示例#9
0
void MaterialSaverDB::saveTemplateChapter( StockMaterial* tmpl )
{
    if( ! tmpl ) {
        kDebug() << "Parameter error, zero material!";
        return;
    }
    dbID id = tmpl->getID();
    dbID chapId = tmpl->chapterId();

    QSqlTableModel model;
    model.setTable("stockMaterial");
    QString templID = id.toString();
    model.setFilter( "matID=" + templID );
    model.select();

    QSqlRecord buffer = model.record();

    if( model.rowCount() > 0)
    {
        kDebug() << "Updating material chapter " << templID << endl;
        buffer = model.record(0);
        buffer.setValue( "chapterID", chapId.toString() );
        model.setRecord(0, buffer);
        model.submitAll();
    } else {
        kDebug() << "Could not update material chapter, not found with id " << templID;
    }
}
示例#10
0
void DlgLogin::on_buttonBox_accepted()
{
    try {

            QByteArray byteArray = ui->txtPassword->text().toUtf8();
            const char* cString = byteArray.constData();
            QString pwd=QString(QCryptographicHash::hash(cString, QCryptographicHash::Md5).toHex());
            QSqlTableModel personal;
            personal.setTable("personal");
            QString filter=QString("login='******' and pwd='%2'").arg(ui->txtUsuario->text().trimmed()).arg(pwd);
            personal.setFilter(filter);
            personal.select();
            if(personal.rowCount()>0){
                MainWindow* w=(MainWindow *) this->parent();
                w->statusBar()->showMessage(tr("Ready"));
                QSqlRecord record=personal.record(0);
                QString userName= QString("%1 %2").arg(record.value("nombre").toString()).arg(record.value("paterno").toString());
                w->setUserName(userName.toUpper());
                qApp->setProperty("user",record.value("id"));
                qApp->setProperty("profile",record.value("perfil_id"));
//                qDebug()<< qApp->property("profile");
            }else{
                ui->lblStateLogin->setText("Usuario o Contraseña errada");
                this->setVisible(true);
            }
    } catch (...) {
        QMessageBox::information(this, "info", "We are in throwExcept()",
                                 QMessageBox::Ok);
    }

}
void QRelation::populateDictionary()
{
    if (!isValid())
        return;

    if (model ==  NULL)
        populateModel();

    QSqlRecord record;
    QString indexColumn;
    QString displayColumn;
    for (int i=0; i < model->rowCount(); ++i) {
        record = model->record(i);

        indexColumn = rel.indexColumn();
        if (m_parent->database().driver()->isIdentifierEscaped(indexColumn, QSqlDriver::FieldName))
            indexColumn = m_parent->database().driver()->stripDelimiters(indexColumn, QSqlDriver::FieldName);

        displayColumn = rel.displayColumn();
        if (m_parent->database().driver()->isIdentifierEscaped(displayColumn, QSqlDriver::FieldName))
            displayColumn = m_parent->database().driver()->stripDelimiters(displayColumn, QSqlDriver::FieldName);

        dictionary[record.field(indexColumn).value().toString()] =
            record.field(displayColumn).value();
    }
    m_dictInitialized = true;
}
示例#12
0
int Database::userCount()
{
    QSqlTableModel model;
    model.setTable("players");
    model.select();
    return model.rowCount();
}
示例#13
0
void MemberDlg::deleteRecords()
{
    QItemSelectionModel *select_mode=view->selectionModel();

    QModelIndexList list = select_mode->selectedRows();
    qDebug()<<"list:"<<list.size();
    if(0 ==  list.count())
    {
        QMessageBox::information(NULL,tr("删除记录"),tr("对不起,请选择至少一条要删除的记录!"),
                                         QMessageBox::Yes);
        return;
    }
    else
    {
        int ret=QMessageBox::information(NULL,tr("删除记录"),tr("您确定要删除该记录?"),
                                         QMessageBox::Yes,QMessageBox::No);
        if(ret==QMessageBox::No)
            return;

       QSqlTableModel tableModel;
       tableModel.setTable("Account");
       for(int i=0; i<list.count();i++)
       {
           int MainID = model->data(model->index(list.at(i).row(),0)).toInt();
           tableModel.setFilter(QString("FamilyMember = %1").arg(MainID));
           tableModel.select();
           tableModel.removeRows(0,tableModel.rowCount()); //先删除Account与该成员关联的记录
       }

       model->removeRows(list.at(0).row(),list.count());
       model->submitAll();
       model->select();
    }
    emit updateFamilyMember();//通知其他窗体更新
}
示例#14
0
void MainWindow::setModel(QTableView *tableViewName, QString modelName, QString tableName, QStringList *tableFields, QString filter, int orderNum)
{
    QSqlTableModel *model;
    if (modelName == "modelEdit") {
        modelEdit = new QSqlTableModel;
        model = modelEdit;
    } else if (modelName == "modelChoose") {
        modelChoose = new QSqlTableModel;
        model = modelChoose;
    } else if (modelName == "modelQ") {
        modelQ = new QSqlTableModel;
        model = modelQ;
    } else if (modelName == "modelQE") {
        modelQE = new QSqlTableModel;
        model = modelQE;
    } else if (modelName == "modelNote") {
        modelNote = new QSqlTableModel;
        model = modelNote;
    } else if (modelName== "modelNotes") {
        modelNotes = new QSqlTableModel;
        model = modelNotes;
    } else {
        return;
    }

    model= new QSqlTableModel(this);
    model->setTable(tableName);
    model->setEditStrategy(QSqlTableModel::OnFieldChange);

    model->setSort(orderNum, Qt::DescendingOrder);

    int tableFieldsNum = tableFields->length();
    for (int i = 0; i < tableFieldsNum; i++) {
        model->setHeaderData(i, Qt::Horizontal, tableFields->at(i));
    }

    tableViewName->setModel(model);
    tableViewName->alternatingRowColors();
    tableViewName->horizontalHeader()->setStretchLastSection(true);

    model->setFilter(filter);
    model->select();
    tableViewName->reset();
    qDebug() << modelName << model << model->rowCount();

    if (modelName == "modelEdit") {
        modelEdit = model;
    } else if (modelName == "modelChoose") {
        modelChoose = model;
    } else if (modelName == "modelQ") {
        modelQ = model;
    } else if (modelName == "modelQE") {
        modelQE = model;
    } else if (modelName == "modelNote") {
        modelNote = model;
    } else if (modelName == "modelNotes") {
        modelNotes = model;
    } else return;
}
QModelIndex MainWindow::indexOfArtist(const QString &artist)
{
    QSqlTableModel *artistModel = model->relationModel(2);

    for (int i = 0; i < artistModel->rowCount(); i++) {
        QSqlRecord record =  artistModel->record(i);
        if (record.value("artist") == artist)
            return artistModel->index(i, 1);
    }
    return QModelIndex();
}
示例#16
0
文件: ToolsFunc.cpp 项目: zzzzzsh/201
bool
ToolsFunc::setExerciseTable( const QString &user, QString &tableName )
{
    QSqlTableModel table;
    table.setTable( "instructor" );
    table.setFilter( QObject::tr( " user = '******'" ).arg( user ) );
    if( !table.select() || !table.rowCount() )
        return false;
    tableName = table.record(0).value( Enum::InstructorSection::Instructor_exercise_tables ).toString();
    return true;
}
示例#17
0
int FacturationIO::getrowoffacturation(QSqlTableModel & modelfacturation,const QString & factureid)
{
    int row = 0;
    for ( int i = 0; i < modelfacturation.rowCount(); ++i)
    {
        if (modelfacturation.data(modelfacturation.index(i,ID_FACTURE),Qt::DisplayRole).toString() == factureid)
        {
              row = i;
            }
        }
    return row;
}
示例#18
0
QSqlTableModel* Dbconnect::select(QString table,QString filter)
{
    qDebug("selectDataSQL");
    QSqlTableModel *model = new QSqlTableModel;
    QString tbName = Db::tbPrefix;
    model->setTable(tbName.append(table));
    if("" != filter){
        model->setFilter(filter);
    }
    model->select();
    qDebug("-------%d",model->rowCount());
    return model;
}
示例#19
0
void EngineerExam::parseQuestions(QString filename) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(filename);
    if (!db.open()) {
	qCritical() << trUtf8("Nie można otworzyć bazy danych!");
    }

    QSqlTableModel question;
    question.setTable("Question");
    question.select();

    QSqlTableModel answers;
    answers.setTable("Answer");
    answers.select();

    QStringList qsl;

    int i = 0;
    while (question.canFetchMore()) {
	question.fetchMore();
	for (; i < question.rowCount(); ++i) {
	    qsl.clear();

	    quint32 id = question.record(i).value("Id").toUInt();
	    QString text = question.record(i).value("Text").toString();
	    Question q;
	    q.setId(id);
	    q.setQuestion(text);

	    answers.setFilter(QString("`id_Question` = %1").arg(id));
	    QString a1 = answers.record(0).value("Text").toString();
	    QString a2 = answers.record(1).value("Text").toString();
	    QString a3 = answers.record(2).value("Text").toString();
	    qsl << a1 << a2 << a3;

	    bool correct1 = answers.record(0).value("IsTrue").toBool();
	    bool correct2 = answers.record(1).value("IsTrue").toBool();
	    bool correct3 = answers.record(2).value("IsTrue").toBool();

	    if (correct1) {
		q.setCorrectAnswer(0);
	    } else if (correct2) {
		q.setCorrectAnswer(1);
	    } else if (correct3) {
		q.setCorrectAnswer(2);
	    }
	    q.setAnswers(qsl);
	    tmpList.append(q);
	}
    }
}
示例#20
0
int Dialog::findArtistId(const QString &artist)
{
    QSqlTableModel *artistModel = model->relationModel(2);
    int row = 0;

    while (row < artistModel->rowCount()) {
        QSqlRecord record = artistModel->record(row);
        if (record.value("artist") == artist)
            return record.value("id").toInt();
        else
            row++;
    }
    return addNewArtist(artist);
}
示例#21
0
void FormPerson::loadLayout(QString tableName)
{
    // Recupero link al database
    QSqlDatabase db = QSqlDatabase::database("ConnectionToDB");
    // Creo un modello sche si riferirà alla tabella delle mail
    QSqlTableModel *model = new QSqlTableModel(this, db);

    // Imposto la tabella a cui si riferirà il modello
    model->setTable(tableName);
    // Imposto un filtro sulla persona a cui la tabella è collegata
    model->setFilter("id_person=" + QString::number(this->personId));
    model->select();

    // Per ciascuna riga della tabella...
    for (int i=0; i<model->rowCount(); i++)
    {
        QHBoxLayout *hbl = new QHBoxLayout();

        // Creo un nuovo oggetto QLineEdit
        QLineEdit *qlineedit = new QLineEdit();
        // Creo un pulsante per la successiva rimozione dell'entry nel database
        RemoveRowFromModel *button = new RemoveRowFromModel(i, model, tableName);
        // Collego il pulante alla funzione di refresh
        QObject::connect(button, SIGNAL(rowRemoved(QString)), this, SLOT(refreshLayout(QString)));

        // Creo un mapper
        QDataWidgetMapper *mapperEmailPerson = new QDataWidgetMapper();

        // Collego al mapper il modello della tabella
        mapperEmailPerson->setModel(model);
        // Aggiungo un mapping tra l'oggetto QLineEdit e il modello
        mapperEmailPerson->addMapping(qlineedit, 1);
        // Posiziono il mapper sull'indice opportuno
        mapperEmailPerson->setCurrentIndex(i);

        // Inserisco il mapper nella lista dei mapper per le email
        getQDataWidgetMapperList(tableName)->append(mapperEmailPerson);



        // qlineedit e button, li visualizzo sulla stessa riga (li inserisco in un layout orizzontale)
        hbl->addWidget(qlineedit);
        hbl->addWidget(button);
        // Inserisco il layout orizzontale nel layout delle mail
        getVerticalLayout(tableName)->addLayout(hbl);

        // Collego il pulsante ad uno slot, in modo che venga gestita la rimozione di una riga dal
        // modello
    }
}
void ChengjiaoQianyueDialog::on_pushButton_clicked()
{
    qDebug() << "add";
    QSqlTableModel * model = this->dbcon->qianyue;
    int row = model->rowCount();
    model->insertRows(row, 1);
    model->setData(model->index(row, 0), this->comboBoxFang->currentText());
    model->setData(model->index(row, 1), this->comboBoxKe->currentText());
    model->setData(model->index(row, 2), this->comboBoxRen->currentText());
    model->setData(model->index(row, 3), this->spinBoxYongjin->text().toInt());
    model->setData(model->index(row, 4), this->comboBoxFen->currentText());
    model->setData(model->index(row, 5), this->spinBoxBianhao->text().toInt());
    model->submitAll();
}
QTreeWidgetItem *CollectionTreeWidget::addAlbum(QString artist, QString album, unsigned int albumId) {
    // Find id in database if we don't have it
    if (albumId == 0) {
         QSqlTableModel *model = service->collectionModel();

         // SQLite used two single quotes to escape a single quote! :)
         QString filter = "artist = '" + QString(artist).replace("'","''") + "' AND "
                          "album = '" + QString(album).replace("'","''") + "'";
         model->setFilter(filter);
         model->select();

         while (model->canFetchMore()) model->fetchMore();
         int total = model->rowCount();
         if (total > 0) {
            albumId = model->record(0).value(model->fieldIndex("id_album")).toInt();
         }
         else {
             qDebug("ERROR: no album found! -- " + model->filter().toUtf8());
             return NULL;
         }
    }

    // Looks for the artist
    QTreeWidgetItem *newAlbumNode; // The node with the album, whether it exists or not
    QTreeWidgetItem *artistItem;
    artistItem = addArtist(artist);

    // Look for album
    for (int i = 0; i < artistItem->childCount(); i++) {
        if (artistItem->child(i)->text(0) == album) {
            newAlbumNode = artistItem->child(i);
            return newAlbumNode;
        }
    }

    // Create our new album node and add it if it was not found
    newAlbumNode = new CollectionTreeWidgetItem(LevelAlbum, albumId, (QTreeWidget*)0);
    newAlbumNode->setText(0, album);
    newAlbumNode->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator);

    // Set icon
    newAlbumNode->setIcon(0, IconFactory::fromTheme("media-cdrom"));

    artistItem->addChild(newAlbumNode);
    artistItem->sortChildren(0, Qt::AscendingOrder);

    return newAlbumNode;
}
示例#24
0
void QRelation::populateDictionary()
{
    if (!isValid())
        return;

    if (model ==  NULL)
        populateModel();

    QSqlRecord record;
    for (int i=0; i < model->rowCount(); ++i) {
        record = model->record(i);
        dictionary[record.field(rel.indexColumn()).value().toString()] =
            record.field(rel.displayColumn()).value();
    }
    m_dictInitialized = true;
}
示例#25
0
bool MaterialSaverDB::saveTemplate( StockMaterial *mat )
{
    bool res = true;

    // Transaktion ?

    QSqlTableModel model;
    model.setTable("stockMaterial");
    QString templID = QString::number( mat->getID() );
    model.setFilter( "matID=" + templID );
    model.select();

    QSqlRecord buffer = model.record();

    if( model.rowCount() > 0)
    {
        kDebug() << "Updating material " << mat->getID() << endl;

        // mach update
        buffer = model.record(0);
        fillMaterialBuffer( buffer, mat, false );
        model.setRecord(0, buffer);
        model.submitAll();
    }
    else
    {
        // insert
        kDebug() << "Creating new material database entry" << endl;

        fillMaterialBuffer( buffer, mat, true );
        model.insertRecord(-1, buffer);
        model.submitAll();

        /* Jetzt die neue Template-ID selecten */
        dbID id = KraftDB::self()->getLastInsertID();
        kDebug() << "New Database ID=" << id.toInt() << endl;

        if( id.isOk() ) {
            mat->setID( id.toInt() );
            templID = id.toString();
        } else {
            kDebug() << "ERROR: Kann AUTOINC nicht ermitteln" << endl;
            res = false;
        }
    }
    return res;
}
示例#26
0
文件: liveinfo.cpp 项目: frankyue/phm
//------------------Above Date--------------------------
void Liveinfo::UpdateRoom(int RoomNum,int change)
{
	QSqlTableModel * updateroom = new QSqlTableModel;		//修改已入住的房间
	updateroom->setTable("Room");
	updateroom->select();	
	for(int i = 0;i < updateroom->rowCount(); ++i)
	{		
		QSqlRecord Roomrecord = updateroom->record(i);
		int check_room = Roomrecord.value("Num").toInt();
		if( check_room == RoomNum )
		{
			Roomrecord.setValue("Live",change);
			updateroom->setRecord(i, Roomrecord);
		}
	}		
	updateroom->submitAll();
}
/// @brief Constructor
CollectionTreeWidget::CollectionTreeWidget()
{
    setColumnCount(1);
    header()->hide(); // hide headers
    setDragEnabled(true);
    setAcceptDrops(true);
    setSelectionMode(QAbstractItemView::ExtendedSelection);

    service = new CollectionService();

    // Add songs that currently exist on database
    QSqlTableModel *artistModel = service->artistModel();
    artistModel->select();

    // TODO: verify if we can put fetchmore() inside the for loop.
    // TODO: put this task in background... URGENT
    while (artistModel->canFetchMore()) artistModel->fetchMore();
    int total = artistModel->rowCount();

    for (int i = 0; i < total; i++) {
        QString artist = artistModel->record(i).value(artistModel->fieldIndex("name")).toString();
        unsigned int id = artistModel->record(i).value(artistModel->fieldIndex("id")).toInt();
        addArtist(artist, id);
    }
    delete artistModel;

    /*
     * TODO: modify the slots in order to add only the artist, not the music.
     *       The album and song must be shown only if the node is already expanded.
     */
    connect(service, SIGNAL(songAdded(Music*)), this, SLOT(addMusic(Music*)));
    connect(service, SIGNAL(songRemoved(unsigned int)), this, SLOT(removeMusic(uint)));
    connect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(doubleClickAt(QModelIndex)));
    connect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(showChildrenOf(QModelIndex)));

    /*
     * We shall emit those signals to show or hide the widget that will
     * give the feedback that the collection is being scanned.
     */
    connect(service, SIGNAL(scanning()), this, SIGNAL(scanning()));
    connect(service, SIGNAL(listUpdated()), this, SIGNAL(listUpdated()));

    // Start service to find new songs and remove the inexistent ones
    service->start(QThread::LowestPriority);
}
示例#28
0
void Database::saveXP(QString &userName, int xp)
{
    QSqlTableModel model;
    model.setTable("user");
    model.select();

    for (int i=0; i<model.rowCount(); ++i)
    {
        QSqlRecord record = model.record(i);
        if (record.value("name").toString()==userName)
        {
            record.setValue("experiencePoints", xp);
            model.setRecord(i, record);
            model.submitAll();
            break;
        }
    }
}
示例#29
0
int Database::loadXP(QString &userName) const
{
    int exp;
    QSqlTableModel model;
    model.setTable("user");
    model.select();

    for (int i=0; i<model.rowCount(); ++i)
    {
        QSqlRecord record = model.record(i);
        if (record.value("name").toString()==userName)
        {
            exp = record.value("experiencePoints").toInt();
            break;
        }
    }
    return exp;
}
示例#30
0
void mainWindow::setupComboBox()
{
    QSqlTableModel* m = new QSqlTableModel();
    m->setTable("Consoles");
    m->removeColumn(0);
    m->select();

    QStringList list;

    for(int i = 0; i < m->rowCount(); i++)
    {
        list.append(m->record(i).value(0).toString());
    }
    list.removeDuplicates();
    list.sort();
    ui->comboConsole->clear();
    ui->comboConsole->addItems(list);
}