예제 #1
0
bool DataModel::LoadData(){

    if(!QSqlDatabase::contains(ConstantsHelper::CONNECTION_NAME)){
        return false;
    }
    QSqlDatabase db = QSqlDatabase::database(ConstantsHelper::CONNECTION_NAME);

    QSqlQuery query(db);

    qDebug()<<ConstantsHelper::SELECT_ALL_SYSTEMS_QUERY;
    if (!query.exec(ConstantsHelper::SELECT_ALL_SYSTEMS_QUERY)){
        return false;
    };

    QSqlRecord rec = query.record();
    int id;
    QString name;
    while(query.next()){
        id = query.value(rec.indexOf("ID")).toInt();
        name = query.value(rec.indexOf("NAME")).toString();
        SpectrumSystem* spSys = new SpectrumSystem(id, name, this);
        m_vSpectrSystem.push_back(spSys);
    }
    return true;
}
void MainWindow::readDb()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
  /*  db.setHostName("localhost");
    db.setDatabaseName("technolo");
    db.setUserName("root");
    db.setPassword("");
*/

 db.setDatabaseName(QDir::current().absoluteFilePath("technologybasic.db"));
        db.open();
        QSqlQuery query1("SELECT * from jos_content order by title;");
        QSqlRecord record = query1.record();
        while (query1.next())
        {
            TitleVar << query1.value(record.indexOf("title")).toString();
            TextVar << query1.value(record.indexOf("introtext")).toString();
        }
        QSqlQuery query2("SELECT * from jos_categories");
        QSqlRecord record1 = query2.record();
        while (query2.next())
        {
           CatVar << query2.value(record1.indexOf("catalias")).toString();
        }

}
예제 #3
0
void QuestInfo::ListNpcClick()
{
	ButtomOpenPClick();
	ui.listQuest->clear();

	QMessageBox a;

	QSqlQuery idNPCquery;
	idNPCquery = DB.query("SELECT id FROM questNPC WHERE name = '"+ui.listNpc->currentItem()->text()+"';");

	QSqlRecord recIdNpc = idNPCquery.record();

	while (idNPCquery.next())
	{
		idNPC = idNPCquery.value(recIdNpc.indexOf("id")).toInt();
	}

	QSqlQuery NameQuest = DB.query("SELECT nameQuest FROM quest WHERE idNPC = '"+IntToQStr(idNPC)+"';");

	QSqlRecord recNameQuest = NameQuest.record();

	while (NameQuest.next())
	{
		ui.listQuest->addItem(NameQuest.value(recNameQuest.indexOf("nameQuest")).toString());
	}
}
예제 #4
0
User MainDataBase::getUser(QString name)
{
    if (db.isOpen())
    {
        QSqlQuery query;


        QString strQuery = QString("SELECT * FROM ScrabbleDataBase WHERE name ='%1'").arg(name);
        bool result = query.exec(strQuery);
        QSqlRecord record = query.record();

        assert(result);

        while (query.next())
        {
            int loseCount = query.value(record.indexOf("loseCount")).toInt();
            int winCount = query.value(record.indexOf("winCount")).toInt();
            int usersCS = query.value(record.indexOf("usersCurrentScore")).toInt();
            int botsCS = query.value(record.indexOf("botsCurrentScore")).toInt();
            QString board = query.value(record.indexOf("currentBoard")).toString();
            string sBoard = "";
            for (int i = 0; i < (int)board.size(); ++i)
                sBoard += board[i].toLatin1();
            return User(name, loseCount, winCount, sBoard, usersCS, botsCS);
        }
        addUser(name);
        return getUser(name);
    }    
}
QVector<CObject*> CKnowledgeDB::getAllObject()
{
    QVector<CObject *> objects;
    QSqlQuery query;
    QSqlRecord record;

    query.prepare("SELECT f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,k FROM object");

    if (!query.exec()) {
        qDebug() << QString("Failed to obtain the object in DB : ") + m_dataBaseName << "\n"
                 << m_dataBase.lastError().text();
        return objects;
    }

    record = query.record();

    while (query.next()) {
        CObject *obj = new CObject();

        for (int i=1; i<=15; ++i) {
            QString featureName = QString("f%1").arg(i);

            QVariant value = query.value(record.indexOf(featureName));
            int testor = getTestor(i);

            obj->addFeature(CFactoryFeature::createFeature(i , value, testor));

        }
        obj->setClass((EClass)query.value(record.indexOf("k")).toInt());
        objects.append(obj);
    }

    return objects;
}
예제 #6
0
/*!
 * \brief Edict2::find Search for a verb in the database, and return its type.
 * \param verb The verb in dictionary form (u-form), eg. 食べる, 飲む, 行く, 来る, etc.
 * \return The type of the verb if found (See: VerbType::EdictType)
 */
EdictType Edict2::find(QString verb)
{
    int result= 0;

        if (verbdb.open()) {
            //qDebug() << "DB connected";
            QSqlQuery query(verbdb);
            query.exec("SELECT * FROM tkanji WHERE kanji='" + verb + "';");
            QSqlRecord record = query.record();
            if (query.next()) {
                result = query.value(record.indexOf("idtype")).toInt();
                //qDebug() << "Verb kanji found" << result;
            }
            else
            {
                query.exec("SELECT * FROM tkana WHERE kana='" + verb + "';");
                record = query.record();
                if (query.next()) {
                    result = query.value(record.indexOf("idtype")).toInt();
                    //qDebug() << "Verb kana found" << result;
                }
            }

        } else {
            qDebug() << "DB not connecting";
        }
    //qDebug() << result;
    verbdb.close();

    return (EdictType) result;
}
예제 #7
0
void DetailMeeting::updateMeeting()
{
    int duration_minute = (meeting_duration->time().hour()*60) + meeting_duration->time().minute();

    QDateTime *date_begin_real = new QDateTime(QDate(meeting_dt_begin->date().year(),meeting_dt_begin->date().month(),meeting_dt_begin->date().day()),meeting_dt_begin->time());

    QString dt_begin;
    dt_begin = QString::number(meeting_dt_begin->date().year()) + "/" + QString::number(meeting_dt_begin->date().month()) + "/" + QString::number(meeting_dt_begin->date().day()) + " " + QString::number(meeting_dt_begin->time().hour()) + ":" + QString::number(meeting_dt_begin->time().minute());

    QString dt_end;
    dt_end = QString::number(meeting_dt_end->date().year()) + "/" + QString::number(meeting_dt_end->date().month()) + "/" + QString::number(meeting_dt_end->date().day()) + " " + QString::number(meeting_dt_end->time().hour()) + ":" + QString::number(meeting_dt_end->time().minute());

    QSqlQuery query;
    query.prepare("SELECT * FROM Meeting where room = :room");
    query.bindValue(":room", id_room);
    query.exec();
    QSqlRecord rec = query.record();

    while(query.next())
    {
        QStringList date_begin = query.value(rec.indexOf("date_begin")).toString().split(" ").at(0).split("/");
        QStringList time_begin = query.value(rec.indexOf("date_begin")).toString().split(" ").at(1).split(":");

        QDate date_begin_edit(date_begin.at(0).toInt(),date_begin.at(1).toInt(),date_begin.at(2).toInt());
        QTime time_begin_edit(time_begin.at(0).toInt(),time_begin.at(1).toInt(),0);

        QStringList date_end_bis = query.value(rec.indexOf("date_end")).toString().split(" ").at(0).split("/");
        QStringList time_end = query.value(rec.indexOf("date_end")).toString().split(" ").at(1).split(":");

        QDate date_end_edit(date_end_bis.at(0).toInt(),date_end_bis.at(1).toInt(),date_end_bis.at(2).toInt());
        QTime time_end_edit(time_end.at(0).toInt(),time_end.at(1).toInt(),0);

        QDateTime datetime_begin(date_begin_edit,time_begin_edit);
        QDateTime datetime_end(date_end_edit,time_end_edit);

        if(date_begin_real->operator >(datetime_begin) && date_begin_real->operator <(datetime_end))
        {
            QMessageBox::critical(this, "Salle indisponible", "La salle selectionné est indisponible.");
            return;
        }
    }

    query.prepare("SELECT * FROM Meeting where id_meeting = :id_meeting");
    query.bindValue(":id_meeting", meeting_id);
    query.exec();
    rec = query.record();
    query.next();

    sendEmailUpdateMeeting(meeting_id,dt_begin);

    query.prepare("Update Meeting set date_begin = :date_begin , date_end =:date_end , duration = :duration WHERE id = :id_meeting");
    query.bindValue(":date_begin", dt_begin);
    query.bindValue(":date_end", dt_end);
    query.bindValue(":duration", duration_minute);
    query.bindValue(":id_meeting", meeting_id);
    query.exec();

    this->close();
    emit notifyRefreshList();
}
예제 #8
0
void BaseSqlTableModel::select() {
    if (!m_bInitialized) {
        return;
    }
    // We should be able to detect when a select() would be a no-op. The DAO's
    // do not currently broadcast signals for when common things happen. In the
    // future, we can turn this check on and avoid a lot of needless
    // select()'s. rryan 9/2011
    // if (!m_bDirty) {
    //     if (sDebug) {
    //         qDebug() << this << "Skipping non-dirty select()";
    //     }
    //     return;
    // }

    if (sDebug) {
        qDebug() << this << "select()";
    }

    QTime time;
    time.start();

    QString columns = m_tableColumnsJoined;
    QString orderBy = orderByClause();
    QString queryString = QString("SELECT %1 FROM %2 %3")
            .arg(columns, m_tableName, orderBy);

    if (sDebug) {
        qDebug() << this << "select() executing:" << queryString;
    }

    QSqlQuery query(m_database);
    // This causes a memory savings since QSqlCachedResult (what QtSQLite uses)
    // won't allocate a giant in-memory table that we won't use at all.
    query.setForwardOnly(true);
    query.prepare(queryString);

    if (!query.exec()) {
        LOG_FAILED_QUERY(query);
        return;
    }

    // Remove all the rows from the table. We wait to do this until after the
    // table query has succeeded. See Bug #1090888.
    // TODO(rryan) we could edit the table in place instead of clearing it?
    if (m_rowInfo.size() > 0) {
        beginRemoveRows(QModelIndex(), 0, m_rowInfo.size()-1);
        m_rowInfo.clear();
        m_trackIdToRows.clear();
        endRemoveRows();
    }

    QSqlRecord record = query.record();
    int idColumn = record.indexOf(m_idColumn);

    QLinkedList<int> tableColumnIndices;
    foreach (QString column, m_tableColumns) {
        Q_ASSERT(record.indexOf(column) == m_tableColumnIndex[column]);
        tableColumnIndices.push_back(record.indexOf(column));
    }
예제 #9
0
QList<DataFile *> DataFileGateway::findFromFilePathList(const QStringList &a_file_path_list)
{
    Q_ASSERT(!a_file_path_list.isEmpty());
    QSqlQuery query(app_database_engine_->appDatabase());

    query.prepare("SELECT * FROM " + table_name_ +
                  " WHERE DATA_FILE_NAME IN ( ':data_file_name_list' )");
    query.bindValue(":data_file_name_list",a_file_path_list.join("','"));
    query.exec();

    QList<DataFile *> data_file_list;

    QSqlRecord record = query.record();
    int data_file_id_col_num = record.indexOf("DATA_FILE_ID");
    int task_id_col_num = record.indexOf("TASK_ID");
    int data_file_name_col_num = record.indexOf("DATA_FILE_NAME");
    int import_time_col_num = record.indexOf("IMPORT_TIME");
    int status_col_num = record.indexOf("STSTUS");

    while(query.next())
    {
        DataFile *a_data_file = new DataFile(this->parent());
        //fillFromRecord();
        a_data_file->data_file_id = query.value(data_file_id_col_num).toInt();
        a_data_file->task_id = query.value(task_id_col_num).toInt();
        a_data_file->data_file_name = query.value(data_file_name_col_num).toString();
        a_data_file->import_time = query.value(import_time_col_num).toString();
        a_data_file->status = query.value(status_col_num).toString();
        data_file_list.append(a_data_file);
    }

    return data_file_list;
}
예제 #10
0
void AutoDJFeature::constructCrateChildModel() {
    // Create a crate table-model with a list of crates that have been added
    // to the auto-DJ queue (and are visible).
    QSqlTableModel crateListTableModel(this, m_pTrackCollection->getDatabase());
    crateListTableModel.setTable(CRATE_TABLE);
    crateListTableModel.setSort(crateListTableModel.fieldIndex(CRATETABLE_NAME),
                                Qt::AscendingOrder);
    crateListTableModel.setFilter(CRATETABLE_AUTODJ_SOURCE + " = 1 AND " + CRATETABLE_SHOW + " = 1");
    crateListTableModel.select();
    while (crateListTableModel.canFetchMore()) {
        crateListTableModel.fetchMore();
    }

    QSqlRecord tableModelRecord = crateListTableModel.record();
    int nameColumn = tableModelRecord.indexOf(CRATETABLE_NAME);
    int idColumn = tableModelRecord.indexOf(CRATETABLE_ID);

    // Create a tree-item for each auto-DJ crate.
    for (int row = 0; row < crateListTableModel.rowCount(); ++row) {
        int id = crateListTableModel.data(
            crateListTableModel.index(row, idColumn)).toInt();
        QString name = crateListTableModel.data(
            crateListTableModel.index(row, nameColumn)).toString();
        m_crateList.append(qMakePair(id, name));

        // Create the TreeItem for this crate.
        TreeItem* item = new TreeItem(name, name, this, m_pCratesTreeItem);
        m_pCratesTreeItem->appendChild(item);
    }
}
예제 #11
0
QDateTime Database::replaceCacheRecordByServerRecord(const QSqlDatabase& dbCache, const QString& table, const QSqlQuery& queryMaster)
{
    QDateTime updated;    
    QSqlRecord record = queryMaster.record();
    int fieldUpdated = record.indexOf("updated");
    if (fieldUpdated == -1)
    {
        fieldUpdated = record.indexOf("created");
    }

    Q_ASSERT(fieldUpdated > -1);
    updated = record.value(fieldUpdated).toDateTime();

    int n = record.count();
    if (n > 1)
    {
        QString sql = QString("REPLACE INTO %1 (").arg(table);
        bool first = true;
        for (int i = 0; i < n; i++)
        {
            if (first)
                first = false;
            else
                sql += ", ";

            sql += record.fieldName(i);
        }
        sql += ") VALUES (";

        first = true;
        for (int i = 0; i < n; i++)
        {
            if (first)
                first = false;
            else
                sql += ", ";

            sql += "?";
        }
        sql += ")";

        QSqlQuery queryCache(dbCache);
        queryCache.setForwardOnly(true);
        queryCache.prepare(sql);

        for (int i = 0; i < n; i++)
        {
            QVariant v(record.value(i));
            if (v.type() == QVariant::DateTime)
                queryCache.bindValue(i, datetimeToString(v.toDateTime()));
            else
                queryCache.bindValue(i, v);
        }

        if (!queryCache.exec())
            throw DatabaseException(queryCache);
    }

    return updated;
}
예제 #12
0
void Model::DataContainer::loadRegions()
{
    #ifdef APP_DEBUG
    qDebug() << "========== Start loading regions ... ==========";
    #endif

    QString sql = "SELECT "
            "regionID, regionName "
            "FROM mapRegions "
            "ORDER BY regionName ASC";

    QSqlQuery query;

    if (!query.exec(sql)) {
        qFatal(qPrintable(tr("SQL error: %s").arg(query.lastError().text())));
    }

    while (query.next()) {
        QSqlRecord rec = query.record();

        DataContainer::regions.insert(
            query.value(rec.indexOf("regionName")).toString(),
            query.value(rec.indexOf("regionID")).toInt());

        #ifdef APP_DEBUG
        qDebug() << "Loaded region: " << query.value(rec.indexOf("regionName")).toString();
        #endif
    }

    #ifdef APP_DEBUG
    qDebug() << "========== End loading regions ==========";
    #endif
}
예제 #13
0
bool QSpectrumValuesModel::LoadData(const int objId){
    m_vL.clear();
    m_vK.clear();

    if(!QSqlDatabase::contains(ConstantsHelper::CONNECTION_NAME)){
        return false;
    }

    QSqlDatabase db = QSqlDatabase::database(ConstantsHelper::CONNECTION_NAME);
    QSqlQuery query(db);

    query.prepare(ConstantsHelper::SELECT_SPECTRUM_QUERY);
    query.bindValue(":object_id", objId);

    if (!query.exec()){
        return false;
    };

    QSqlRecord rec = query.record();
    int id;
    double l;
    double k;
    while(query.next()){
        id = query.value(rec.indexOf("ID")).toInt();
        l = query.value(rec.indexOf("L")).toDouble();
        k = query.value(rec.indexOf("K")).toDouble();
        m_vL.push_back(l);
        m_vK.push_back(k);
        //m_dqCount++;
    }

    return true;
}
예제 #14
0
bool SpectrumClass::LoadData(){
    if(!QSqlDatabase::contains(ConstantsHelper::CONNECTION_NAME)){
        return false;
    }

    QSqlDatabase db = QSqlDatabase::database(ConstantsHelper::CONNECTION_NAME);
    QSqlQuery query(db);

    query.prepare(ConstantsHelper::SELECT_OBJECTS_QUERY);
    query.bindValue(":class_id", GetID());

    if (!query.exec()){
        return false;
    };

    QSqlRecord rec = query.record();
    int id;
    QString name;
    while(query.next()){
        id = query.value(rec.indexOf("ID")).toInt();
        name = query.value(rec.indexOf("NAME")).toString();
        SpectrumObject* spObj = new SpectrumObject(id, name, this);
        m_vSpectrObj.push_back(spObj);
    }

    return true;
}
예제 #15
0
void WorkLoader::mixerLoadWork(int mixer){
	if(mWork >= 0 && mixer >= 0 && (unsigned int)mixer < mNumMixers){
		if(mLoaderThreads[mixer]->isRunning()){
			qWarning("Mixer %d is currently loading a file", mixer);
			return;
		}
		//build up query
		QString fileQueryStr(cFileQueryString);
		QString workQueryStr(cWorkInfoQueryString);
		QString id;
		id.setNum(mWork);
		fileQueryStr.append(id);
		workQueryStr.append(id);
		//execute
		mFileQuery.exec(fileQueryStr);
		QSqlRecord rec = mFileQuery.record();
		int audioFileCol = rec.indexOf("audio_file");
		int beatFileCol = rec.indexOf("beat_file");
		//if we can grab it
		if(mFileQuery.first()){
			QString audiobufloc = mFileQuery.value(audioFileCol).toString();
			QString beatbufloc = mFileQuery.value(beatFileCol).toString();

			//if we're syncing to this mixer then change the sync source
			if(mMixerPanelModel->master()->syncSource() == (unsigned int)(mixer + 1))
				mMixerPanelModel->master()->setSyncSource(0);

			//emit a signal to unload the buffers of this mixer
			emit(mixerLoaded(mixer, NULL, NULL));
			//reset the mixer channel
			mMixerPanelModel->mixerChannels()->at(mixer)->reset();
			//use a thread to load the stuff!
			mLoaderThreads[mixer]->start(mixer, mWork, audiobufloc, beatbufloc);

			//indicate that we're loading
			mWorkInfoQuery.exec(workQueryStr);
			if(mWorkInfoQuery.first()){
				rec = mWorkInfoQuery.record();
				int titleCol = rec.indexOf("title");
				int artistCol = rec.indexOf("artist");
				QString loadingArtist("loading: ");
				QString loadingTitle("loading: ");

				loadingArtist.append(mWorkInfoQuery.value(artistCol).toString());
				loadingTitle.append(mWorkInfoQuery.value(titleCol).toString());

				mMixerPanelView->mixerChannels()->at(mixer)->DJMixerWorkInfo()->setArtistText(
						loadingArtist);
				mMixerPanelView->mixerChannels()->at(mixer)->DJMixerWorkInfo()->setTitleText(
						loadingTitle);
				mMixerPanelModel->mixerChannels()->at(mixer)->setWork(-1);
			}
			
		} else {
			//XXX ERROR
		}
	} else {
		//XXX no work selected
	}
}
예제 #16
0
DataFile *DataFileGateway::findFromFilePath(const QString &a_file_path)
{
    Q_ASSERT(!a_file_path.isEmpty());
    QSqlQuery query(app_database_engine_->appDatabase());

    query.prepare("SELECT * FROM " + table_name_ +
                  " WHERE DATA_FILE_NAME=':data_file_name' ");
    query.bindValue(":data_file_name",a_file_path);
    query.exec();


    QSqlRecord record = query.record();
    int data_file_id_col_num = record.indexOf("DATA_FILE_ID");
    int task_id_col_num = record.indexOf("TASK_ID");
    int data_file_name_col_num = record.indexOf("DATA_FILE_NAME");
    int import_time_col_num = record.indexOf("IMPORT_TIME");
    int status_col_num = record.indexOf("STSTUS");

    if(query.next())
    {
        DataFile *a_data_file = new DataFile(this->parent());
        //fillFromRecord();
        a_data_file->data_file_id = query.value(data_file_id_col_num).toInt();
        return a_data_file;
    }

    return 0;
}
예제 #17
0
void WorkLoader::setWork(unsigned int mixer_index, 
		int work,
		DataJockey::AudioBufferPtr audio_buffer, 
		DataJockey::BeatBufferPtr beat_buffer){
	//build up query
	QSqlRecord rec;
	QString workQueryStr(cWorkInfoQueryString);
	QString id;
	id.setNum(work);
	workQueryStr.append(id);

	emit(mixerLoaded(mixer_index, audio_buffer, beat_buffer));
	emit(mixerLoaded(mixer_index, work));
	
	//set the info
	mWorkInfoQuery.exec(workQueryStr);
	if(mWorkInfoQuery.first()){
		rec = mWorkInfoQuery.record();
		int titleCol = rec.indexOf("title");
		int artistCol = rec.indexOf("artist");
		mMixerPanelView->mixerChannels()->at(mixer_index)->DJMixerWorkInfo()->setArtistText(
				mWorkInfoQuery.value(artistCol).toString()
				);
		mMixerPanelView->mixerChannels()->at(mixer_index)->DJMixerWorkInfo()->setTitleText(
				mWorkInfoQuery.value(titleCol).toString()
				);
		mMixerPanelModel->mixerChannels()->at(mixer_index)->setWork(work);
	}
}
예제 #18
0
파일: dbutil.cpp 프로젝트: mdda/mythtv
/** \fn DBUtil::CheckRepairStatus(MSqlQuery &query)
 *  \brief Parse the results of a CHECK TABLE or REPAIR TABLE run.
 *
 *   This function reads the records returned by a CHECK TABLE or REPAIR TABLE
 *   run and determines the status of the table(s). The query should have
 *   columns Table, Msg_type, and Msg_text.
 *
 *   The function properly handles multiple records for a single table. If the
 *   last record for a given table shows a status (Msg_type) of OK (Msg_text),
 *   the table is considered OK, even if an error or warning appeared before
 *   (this could be the case, for example, when an empty table is crashed).
 *
 *  \param query An already-executed CHECK TABLE or REPAIR TABLE query whose
 *               results should be parsed.
 *  \return A list of names of not-OK (errored or crashed) tables
 *  \sa DBUtil::CheckTables(const bool, const QString)
 *  \sa DBUtil::RepairTables(const QStringList)
 */
QStringList DBUtil::CheckRepairStatus(MSqlQuery &query)
{
    QStringList tables;
    QSqlRecord record = query.record();
    int table_index = record.indexOf("Table");
    int type_index = record.indexOf("Msg_type");
    int text_index = record.indexOf("Msg_text");
    QString table, type, text, previous_table;
    bool ok = true;
    while (query.next())
    {
        table = query.value(table_index).toString();
        type = query.value(type_index).toString();
        text = query.value(text_index).toString();
        if (table != previous_table)
        {
            if (!ok)
            {
                tables.append(previous_table);
                ok = true;
            }
            previous_table = table;
        }
        // If the final row shows status OK, the table is now good
        if ("status" == type.toLower() && "ok" == text.toLower())
            ok = true;
        else if ("error" == type.toLower() ||
                 ("status" == type.toLower() && "ok" != text.toLower()))
            ok = false;
    }
    // Check the last table in the list
    if (!ok)
        tables.append(table);
    return tables;
}
예제 #19
0
void EventGoersView::configHeaders(){
  QSqlRecord record = eventGoersModel->record();
  int usernameIndex = record.indexOf(DataStore::getEventGoerUsernameColName());
  int idIndex = record.indexOf(DataStore::getEventGoersIdColName());
  setColumnHidden(idIndex, true);
  eventGoersModel->setHeaderData(
    usernameIndex, Qt::Horizontal, tr("User"), Qt::DisplayRole);
}
void ATMLoginToMainForm::on_button_login_clicked()
{
    bool flag_id  = false;
    bool flag_pwd = false;
    int index_card_id;
    int index_card_pwd;
    QString card_id;
    QString card_pwd;
    QSqlQuery query;
    QSqlRecord record;

    card_id = ui->line_edit_id->text();
    card_pwd   = ui->line_edit_pwd->text();

    if (!ATMConnectDatabase::openDatabase()) {
        QMessageBox::warning(this, tr("错误"), tr("打开数据库失败!"), tr("是"));
        return ;
    }

    query.exec("select * from card_information");

    while (query.next()) {
        record = query.record();
        index_card_id = record.indexOf("card_id");
        index_card_pwd   = record.indexOf("card_pwd");
        if (query.value(index_card_id).toString() == card_id) {
            flag_id = true;
            if (query.value(index_card_pwd).toString() == card_pwd) {
                g_card_id  = card_id;
                g_card_pwd = card_pwd;
                flag_pwd = true;
                ui->line_edit_id->clear();
                ui->line_edit_pwd->clear();
                ATMMainFunctionForm *atm_main_function =
                    new ATMMainFunctionForm();
                atm_main_function->show();
                atm_main_function->move(
                    (QApplication::desktop()->width()  -
                     atm_main_function->width())  / 2,
                    (QApplication::desktop()->height() -
                     atm_main_function->height()) / 2);
                this->close();
            }
        }
    }

    if (flag_id && !flag_pwd) {
        QMessageBox::warning(this, tr("错误"), tr("密码错误!"), tr("是"));
        ui->line_edit_pwd->clear();
        return ;
    }
    else if (!flag_id && !flag_pwd){
        QMessageBox::warning(this, tr("错误"), tr("账户或密码错误!"), tr("是"));
        ui->line_edit_id->clear();
        ui->line_edit_pwd->clear();
        return ;
    }
}
예제 #21
0
void SongListView::configHeaders(){
  QSqlRecord record = songListEntryModel->record();
  int libIdIndex = record.indexOf(DataStore::getLibIdAlias());
  int idIndex = record.indexOf(DataStore::getSongListEntryIdColName());
  int durationIndex = record.indexOf(DataStore::getLibDurationColName());
  setColumnHidden(libIdIndex, true);
  setColumnHidden(idIndex, true);
  resizeColumnToContents(durationIndex);
}
예제 #22
0
void LibraryView::configureColumns(){
  QSqlRecord record = libraryModel->record();
  int idIndex = record.indexOf(DataStore::getLibIdColName());
  int isDeletedIndex = record.indexOf(DataStore::getLibIsDeletedColName());
  int syncStatusIndex = record.indexOf(DataStore::getLibSyncStatusColName());
  int durationIndex = record.indexOf(DataStore::getLibDurationColName());
  setColumnHidden(idIndex, true);
  setColumnHidden(isDeletedIndex, true); 
  setColumnHidden(syncStatusIndex, true); 
  resizeColumnToContents(durationIndex);
}
예제 #23
0
void AvailableMusicView::configHeaders(){
  QSqlRecord record = availableMusicModel->record();
  int syncIndex =   
    record.indexOf(DataStore::getAvailableEntrySyncStatusColName());
  int libIdIndex =
    record.indexOf(DataStore::getAvailableEntryLibIdColName());
  int durationIndex = record.indexOf(DataStore::getLibDurationColName());
  setColumnHidden(syncIndex, true);
  setColumnHidden(libIdIndex, true);
  resizeColumnToContents(durationIndex);
}
예제 #24
0
파일: cdatabase.cpp 프로젝트: slums/QNoise
void CDatabase::getValuesFromDatabase()
{
    QSqlQuery query;
    if (!query.exec("SELECT * FROM mainSettings"))
    {
        qDebug() << "Select error : mainSettings";
        qDebug() << db.lastError();
    }
    else
    {
        if (!query.next())
        {
            qDebug() << "Some error with database.. I expected some values but got none..";
            qDebug() << db.lastError();
        }
        else
        {
            QSqlRecord r = query.record();
            int fieldNo1 = r.indexOf("last_online");
            int fieldNo2 = r.indexOf("lyrics_online");
            int fieldNo3 = r.indexOf("last_user");
            int fieldNo4 = r.indexOf("last_pass");
            int fieldNo5 = r.indexOf("repeat");
            int fieldNo6 = r.indexOf("shuffle");

            QString tmpValue;
            tmpValue = query.value(fieldNo1).toString();
            lastFmOnline = tmpValue.toInt();
            qDebug() << "Set last_online to" << tmpValue;

            tmpValue = query.value(fieldNo2).toString();
            lyricsOnline = tmpValue.toInt();
            qDebug() << "Set lyrics_online to" << tmpValue;

            tmpValue = query.value(fieldNo3).toString();
            lastFmUser = tmpValue;
            qDebug() << "Set last_user to" << tmpValue;

            tmpValue = query.value(fieldNo4).toString();
            lastFmPassword = tmpValue;
            qDebug() << "Set last_pass to ...";

            tmpValue = query.value(fieldNo5).toString();
            repeat = tmpValue.toInt();
            qDebug() << "Set repeat to" << tmpValue;

            tmpValue = query.value(fieldNo6).toString();
            shuffle = tmpValue.toInt();
            qDebug() << "Set shuffle to" << tmpValue;
        }
    }
}
void BorrowerSearch::searchBorrowers() {
        QSettings settings;
        QString borrowersDbFilePath = settings.value("borrowersDbFilePath").toString();

        // If borrowersDbFilePath is not set,
        // Default to APP_DIR/borrowers.db so the program does not crash.
        if ( borrowersDbFilePath.isEmpty() ) {
            borrowersDbFilePath = "borrowers.db";
        }

	clearResults();

	QString lastnameSearch = nameLast->text();
	QString firstnameSearch = nameFirst->text();

	QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );

        db.setDatabaseName( borrowersDbFilePath );

	if ( db.open() ) {
		QString borrowersQuery = "SELECT * FROM borrowers WHERE firstname LIKE '" 
						+ firstnameSearch + "%' AND surname LIKE '" + lastnameSearch 
						+ "%' ORDER BY firstname ASC";
		QSqlQuery query( borrowersQuery );
	
		qDebug() << "Borrower Search SQL: " + borrowersQuery;
	
		QSqlRecord record = query.record();
		while (query.next()) {
			QString lastname = query.value(record.indexOf("surname")).toString();
			QString firstname = query.value(record.indexOf("firstname")).toString();
			QString dateofbirth = query.value(record.indexOf("dateofbirth")).toString();
			QString streetaddress = query.value(record.indexOf("address")).toString();
			QString city = query.value(record.indexOf("city")).toString();
			QString state = query.value(record.indexOf("state")).toString();
			QString zipcode = query.value(record.indexOf("zipcode")).toString();
			QString cardnumber = query.value(record.indexOf("cardnumber")).toString();
			QString address = streetaddress + "\n" + city + ", " + state + "\n" + zipcode;
	
			qDebug() << query.at() << ":" << lastname << "," << firstname;
	
			addSearchResult( lastname, firstname, dateofbirth, address, cardnumber );
		}

		qDebug() << "Search Complete";

	} else {
		qDebug() << db.lastError();
		qFatal( "Failed to connect." );

		QMessageBox::warning(this, tr("Cannot Borrowers File"),
                                   tr("Unable to open the file borrowers.db.\n"
									"This file is needed in order to search for borrowers."
									"Please create the borrowers.db file and place it in"
									"the same directory as this program.\n\n"),
                                   QMessageBox::Ok);
	}

}
예제 #26
0
void PlaylistFeature::buildPlaylistList() {
    m_playlistList.clear();

    QString queryString = QString(
        "CREATE TEMPORARY VIEW IF NOT EXISTS PlaylistsCountsDurations "
        "AS SELECT "
        "  Playlists.id as id, "
        "  Playlists.name as name, "
        "  COUNT(library.id) as count, "
        "  SUM(library.duration) as durationSeconds "
        "FROM Playlists "
        "LEFT JOIN PlaylistTracks ON PlaylistTracks.playlist_id = Playlists.id "
        "LEFT JOIN library ON PlaylistTracks.track_id = library.id "
        "WHERE Playlists.hidden = 0 "
        "GROUP BY Playlists.id;");
    QSqlQuery query(m_pTrackCollection->getDatabase());
    if (!query.exec(queryString)) {
        LOG_FAILED_QUERY(query);
    }

    // Setup the sidebar playlist model
    QSqlTableModel playlistTableModel(this, m_pTrackCollection->getDatabase());
    playlistTableModel.setTable("PlaylistsCountsDurations");
    playlistTableModel.setSort(playlistTableModel.fieldIndex("name"),
                               Qt::AscendingOrder);
    playlistTableModel.select();
    while (playlistTableModel.canFetchMore()) {
        playlistTableModel.fetchMore();
    }
    QSqlRecord record = playlistTableModel.record();
    int nameColumn = record.indexOf("name");
    int idColumn = record.indexOf("id");
    int countColumn = record.indexOf("count");
    int durationColumn = record.indexOf("durationSeconds");

    for (int row = 0; row < playlistTableModel.rowCount(); ++row) {
        int id = playlistTableModel.data(
            playlistTableModel.index(row, idColumn)).toInt();
        QString name = playlistTableModel.data(
            playlistTableModel.index(row, nameColumn)).toString();
        int count = playlistTableModel.data(
            playlistTableModel.index(row, countColumn)).toInt();
        int duration = playlistTableModel.data(
            playlistTableModel.index(row, durationColumn)).toInt();
        m_playlistList.append(qMakePair(id, QString("%1 (%2) %3")
                                        .arg(name, QString::number(count),
                                             Time::formatSeconds(duration, false))));
    }
}
예제 #27
0
void DB::format_string_by_id(int work_id, QString& info) throw(std::runtime_error) {
  //build up query
  MySqlQuery query(get());
  query.prepare(cWorkInfoQuery);
  query.bindValue(":id", work_id);

  //execute
  if(!(query.exec() && query.first()))
    return;

  QSqlRecord rec = query.record();
  info.replace("$artist", query.value(rec.indexOf("artist")).toString());
  info.replace("$title", query.value(rec.indexOf("title")).toString());
  info.replace("$album", query.value(rec.indexOf("album")).toString());
}
예제 #28
0
void CrateFeature::buildCrateList() {
    m_crateList.clear();

    QString queryString = QString(
        "CREATE TEMPORARY VIEW IF NOT EXISTS CratesCountsDurations "
        "AS SELECT "
        "  crates.id as id, "
        "  crates.name as name, "
        "  COUNT(library.id) as count, "
        "  SUM(library.duration) as durationSeconds "
        "FROM crates "
        "LEFT JOIN crate_tracks ON crate_tracks.crate_id = crates.id "
        "LEFT JOIN library ON crate_tracks.track_id = library.id "
        "WHERE show = 1 "
        "GROUP BY crates.id;");
    QSqlQuery query(m_pTrackCollection->getDatabase());
    if (!query.exec(queryString)) {
        LOG_FAILED_QUERY(query);
    }

    QSqlTableModel crateListTableModel(this, m_pTrackCollection->getDatabase());
    crateListTableModel.setTable("CratesCountsDurations");
    crateListTableModel.setSort(crateListTableModel.fieldIndex("name"),
                                Qt::AscendingOrder);
    crateListTableModel.select();
    while (crateListTableModel.canFetchMore()) {
        crateListTableModel.fetchMore();
    }
    QSqlRecord record = crateListTableModel.record();
    int nameColumn = record.indexOf("name");
    int idColumn = record.indexOf("id");
    int countColumn = record.indexOf("count");
    int durationColumn = record.indexOf("durationSeconds");

    for (int row = 0; row < crateListTableModel.rowCount(); ++row) {
        int id = crateListTableModel.data(
            crateListTableModel.index(row, idColumn)).toInt();
        QString name = crateListTableModel.data(
            crateListTableModel.index(row, nameColumn)).toString();
        int count = crateListTableModel.data(
            crateListTableModel.index(row, countColumn)).toInt();
        int duration = crateListTableModel.data(
            crateListTableModel.index(row, durationColumn)).toInt();
        m_crateList.append(qMakePair(id, QString("%1 (%2) %3")
                                     .arg(name, QString::number(count),
                                          Time::formatSeconds(duration, false))));
    }
}
예제 #29
0
QString Global::QueryUserFromDb(QString username, QString password)
{
	int indexUserID;
	QString userID;

	QSqlQuery sql_query; 
	QSqlRecord rec;

	QString select_sql = "SELECT * FROM user WHERE BINARY username = '******' AND BINARY password = '******'";
	sql_query.prepare(select_sql);
	if(!sql_query.exec())
	{
		qWarning() << "\t" <<"Select user failed! ";
		return QString("");
	}
	else
	{
		rec = sql_query.record();
		if (sql_query.next())
		{
			indexUserID = rec.indexOf(QString("ID"));
			userID = sql_query.value(indexUserID).toString();
			return userID;
		}
		return QString("");
	}
}
예제 #30
0
파일: mainwindow.cpp 프로젝트: proton/lau
void MainWindow::setModel()
{
    if(QSqlDatabase::contains(QSqlDatabase::defaultConnection)) {
        db = QSqlDatabase::database();
    } else {
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("d:\\db.db3");
    }
    if (db.open())
    {
    QSqlQueryModel *model = new QSqlQueryModel();
    model->setQuery("SELECT title FROM databases");

    ui->listView->setModel(model);

    }else{
        qDebug()<<QObject::trUtf8("Ошибка");
    }
    QSqlQuery query;

    if (query.exec("SELECT * FROM settings WHERE Setting = 'path';"))
    {
         QSqlRecord rec = query.record();
        while (query.next())
        {
        ui->label_path->setText(query.value(rec.indexOf("VALUE")).toString());
        }
    }else{
        ui->label_path->setText(QObject::tr("Невозможно прочитать путь к файлам"));
    }
}