コード例 #1
0
/*----------------------------------------------------------------------------*/
void SelSessionBox::onSessionChanged(QModelIndex idx)
{
  QSqlQuery q = sessionModel->query();
  q.seek(idx.row());
  int id = q.value(0).toInt();
  database->measureSession(id, m_session);
}
コード例 #2
0
void TablePrivate::init()
{
    Q_Q(Table);

    q->setTable(name);
    q->setEditStrategy(QSqlTableModel::OnFieldChange);
    q->select();

    QSqlRecord columnNames = q->record();
    int columnCount = columnNames.count();
    columns.reserve(columnCount);
    for(int i = 0; i < columnCount; ++i) {
        Column *column = new Column(columnNames.field(i), q);
        column->setIndex(i);
        columns.append(column);
        columnsByName.insert(column->name(), column);
    }

    while(q->canFetchMore())
        q->fetchMore();

    QSqlQuery query = q->query();
    int rowCount = q->rowCount();
    int idIndex = q->record().indexOf(QLatin1String("id"));
    int id = 0;
    rows.reserve(rowCount);
    rowsById.reserve(rowCount);
    for(int i = 0; i < rowCount; ++i) {
        query.seek(i);
        id = query.value(idIndex).toInt();
        Row *row = new Row(i, id, q);
        rows.append(row);
        rowsById.insert(id, row);
    }
}
コード例 #3
0
ファイル: OrderAdapter.cpp プロジェクト: julianandreou/pos
int OrderAdapter::getOrderLineFromOrderIdAndByModelIndex(int orderId, const QModelIndex& modelIndex)
{
	QModelIndex index = modelIndex;

	if (index.isValid())
	{
		std::ostringstream tQuery;

		//! TODO - actually query model (instead of duplicating + assumption)
		tQuery << "(SELECT ALL bLine.id, pizza.fqn, bLine.price FROM pizza, purchasable purch, bikeLine bLine " <<
				"WHERE pizza.id = purch.pizzaId AND bLine.pRef = purch.id " <<
				"AND bLine.oRef = " << orderId <<
				") UNION ALL (" <<
				"SELECT ALL bLine.id, menu.name, bLine.price FROM menu, bikeLine bLine, misc, purchasable " <<
				"WHERE menu.id = misc.menuId AND misc.id = purchasable.pizzaId AND bLine.pRef = purchasable.id " <<
				"AND bLine.oRef = " << orderId << ") ORDER BY id ASC;";

		QSqlQuery query;
		query.prepare(tQuery.str().c_str());
		query.exec();

		query.seek(index.row());
		int id = query.value(0).toInt();

		return id;
	}

	return -1;
}
コード例 #4
0
ファイル: mainwindow.cpp プロジェクト: firephoenix/wmanual
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());//读取广告
            }
        }
    }
}
コード例 #5
0
ファイル: database.cpp プロジェクト: idxExtropy/duel-reality
const float Database::spriteActionTime(int index) const
{
    QSqlQuery query;
    query.exec("SELECT actionTime FROM sprite");
    query.seek(index-1);
    float actionTime = query.value(0).toInt();
    return actionTime;
}
コード例 #6
0
ファイル: database.cpp プロジェクト: idxExtropy/duel-reality
const int Database::spriteActionRate(int index) const
{
    QSqlQuery query;
    query.exec("SELECT actionRate FROM sprite");
    query.seek(index-1);
    int actionRate = query.value(0).toInt();
    return actionRate;
}
コード例 #7
0
ファイル: database.cpp プロジェクト: idxExtropy/duel-reality
const int Database::spriteMovementRange(int index) const
{
    QSqlQuery query;
    query.exec("SELECT movementRange FROM sprite");
    query.seek(index-1);
    int movementRange = query.value(0).toInt();
    return movementRange;
}
コード例 #8
0
ファイル: database.cpp プロジェクト: idxExtropy/duel-reality
const int Database::spriteAttackRange(int index) const
{
    QSqlQuery query;
    query.exec("SELECT attackRange FROM sprite");
    query.seek(index-1);
    int attackRange = query.value(0).toInt();
    return attackRange;
}
コード例 #9
0
ファイル: database.cpp プロジェクト: idxExtropy/duel-reality
const int Database::spriteHitPoints(int index) const
{
    QSqlQuery query;
    query.exec("SELECT hitPoints FROM sprite");
    query.seek(index-1);
    int HP = query.value(0).toInt();
    return HP;
}
コード例 #10
0
ファイル: database.cpp プロジェクト: idxExtropy/duel-reality
const int Database::spriteAttackPower(int index) const
{
    QSqlQuery query;
    query.exec("SELECT attackPower FROM sprite");
    query.seek(index-1);
    int AP = query.value(0).toInt();
    return AP;
}
コード例 #11
0
ファイル: database.cpp プロジェクト: idxExtropy/duel-reality
QString Database::spriteFileName(int index) const
{
    QSqlQuery query;
    query.exec("SELECT imageFileName FROM sprite");
    query.seek(index-1);
    QString fileName = query.value(0).toString();
    return fileName;
}
コード例 #12
0
ファイル: database.cpp プロジェクト: idxExtropy/duel-reality
QString Database::userName(int index) const
{
    QSqlQuery query;
    query.exec("SELECT name FROM user");
    query.seek(index-1);
    QString name = query.value(0).toString();
    return name;
}
コード例 #13
0
//--------------------utech--------------------utech--------------------utech--------------------
bool USkladProgOptions::organizCinaZPodatkom()
{
	QSqlQuery query;
	query.exec("SELECT CinaZPodatkom FROM orgInfo WHERE PidprId=1");
	if (query.seek(0)){
		return query.value(0).toBool();
	}
	else{
		qDebug() << "SQL Table orgInfo has no record with id=1.";
		return true;
	}
}
コード例 #14
0
/*
	Значення податків:
		0. Фіксований патент ПП
		1. ПДВ
		2. Єдиний податок
*/
int USkladProgOptions::organizPodatok()
{
	QSqlQuery query;
	query.exec("SELECT Podatok FROM orgInfo WHERE PidprId=1");
	if (query.seek(0)){
		return query.value(0).toInt();
	}
	else{
		qDebug() << "SQL Table orgInfo has no record with id=1.";
		return -1;
	}
}
コード例 #15
0
//--------------------utech--------------------utech--------------------utech--------------------
double USkladProgOptions::organizVidsotokPodatku()
{
	QSqlQuery query;
	query.exec("SELECT PodatokVal FROM orgInfo WHERE PidprId=1");
	if (query.seek(0)){
		return query.value(0).toDouble();
	}
	else{
		qDebug() << "SQL Table orgInfo has no record with id=1.";
		return 0;
	}
}
コード例 #16
0
ファイル: historykeeper.cpp プロジェクト: CuiZhicheng/qTox
HistoryKeeper::HistoryKeeper(GenericDdInterface *db_) :
    oldDb(db_)
{
    /*
     DB format
     chats:
      * name -> id map
       id      -- auto-incrementing number
       name    -- chat's name (for user to user conversation it is opposite user public key)
       ctype   -- chat type, reserved for group chats

     aliases:
      * user_id -> id map
       id       -- auto-incrementing number
       user_id  -- user's public key
       av_hash  -- hash of user's avatar
       avatar   -- user's avatar

     history:
       id           -- auto-incrementing number
       timestamp
       chat_id      -- current chat ID (resolves from chats table)
       sender       -- sender's ID (resolves from aliases table)
       message
       alias        -- sender's alias in
    */

    // for old tables:
    QSqlQuery ans = oldDb->exec("SELECT seq FROM sqlite_sequence WHERE name=\"history\";");
    if (ans.first())
    {
        int idMax = ans.value(0).toInt();
        QSqlQuery ret = oldDb->exec("SELECT seq FROM sqlite_sequence WHERE name=\"sent_status\";");
        int idCur = 0;
        if (ret.first())
            idCur = ret.value(0).toInt();

        if (idCur != idMax)
        {
            QString cmd = QString("INSERT INTO sent_status (id, status) VALUES (%1, 1);").arg(idMax);
            oldDb->exec(cmd);
        }
    }
    //check table stuct
    ans = oldDb->exec("PRAGMA table_info (\"history\")");
    ans.seek(5);
    if (!ans.value(1).toString().contains("alias"))
    {
        //add collum in table
        oldDb->exec("ALTER TABLE history ADD COLUMN alias TEXT");
        qDebug() << "Struct DB updated: Added column alias in table history.";
    }
}
コード例 #17
0
ファイル: dbfunc.cpp プロジェクト: RudolfCardinal/camcops
bool DbFunc::execQuery(QSqlQuery& query, const QString& sql,
                       const ArgList& args)
{
    // Executes an existing query (in place) with the supplied SQL/args.
    // THIS IS THE MAIN POINT THROUGH WHICH ALL QUERIES SHOULD BE EXECUTED.
    query.prepare(sql);
    addArgs(query, args);

#ifdef DEBUG_SQL_QUERY
    {
        qDebug() << "Executing:" << qUtf8Printable(sql);
        QDebug debug = qDebug().nospace();
        debug << "... args: ";
        DebugFunc::debugConcisely(debug, args);
    }  // endl on destruction
#endif

    bool success = query.exec();
#ifdef DEBUG_QUERY_END
    qDebug() << "... query finished";
#endif
    if (!success) {
        qCritical() << "Query failed; error was:" << query.lastError();
    }
#ifdef DEBUG_SQL_RESULT
    if (success && query.isSelect() && !query.isForwardOnly()) {
        qDebug() << "Resultset preview:";
        int row = 0;
        while (query.next()) {
            QDebug debug = qDebug().nospace();
            QSqlRecord rec = query.record();
            int ncols = rec.count();
            debug << "... row " << row << ": ";
            for (int col = 0; col < ncols; ++col) {
                if (col > 0) {
                    debug << "; ";
                }
                debug << rec.fieldName(col) << "=";
                DebugFunc::debugConcisely(debug, query.value(col));
            }
            ++row;
        }  // endl on destruction
        if (row == 0) {
            qDebug() << "<no rows>";
        }
        query.seek(QSql::BeforeFirstRow);  // the original starting position
    }
#endif
    return success;
    // The return value is boolean (success?).
    // Use query.next() to iterate through a result set; see
    // http://doc.qt.io/qt-4.8/sql-sqlstatements.html
}
コード例 #18
0
ファイル: execut_window.cpp プロジェクト: xuezeao/git_program
void Execut_window::getAllCount(void)
{
    QSqlQuery query;
    int temporaryA = 0;
    int temporaryB = 0;
    int k = 0;
    int choiceModel = 0;//选择drawerNo的位置
    saveDrawer[0] = 0;

    if (execute_V->execute_model == 1)//入柜
    {
        choiceModel = 17;
    }
    else if (execute_V->execute_model == 2)//还
    {
        choiceModel = 9;
    }
    else if ((execute_V->execute_model == 4) || (execute_V->execute_model == 6))//替换
    {
        executeInfoError(1,"请取出试剂");
        choiceModel = 8;
    }

    if ((execute_V->execute_model == 2) || (execute_V->execute_model == 1) ||\
            (execute_V->execute_model == 4) || (execute_V->execute_model == 6))
    {

        query.exec(QString("SELECT * from %1 ORDER BY drawerNo ASC").arg(execute_V->T_executeTable));

        query.last();
        execute_V->acountRow = query.at()+1;//0

        for(int i = 0; i < execute_V->acountRow; i++)
        {
            query.seek(i);        
            temporaryA = query.value(choiceModel).toInt();
            if(temporaryA != temporaryB)
            {
                temporaryB = temporaryA;
                k++;
                saveDrawer[0]=k;
                saveDrawer[k]=temporaryB;
            }


        }



    }
}
コード例 #19
0
static QScriptValue qmlsqldatabase_item(QScriptContext *context, QScriptEngine *engine)
{
    QSqlQuery query = qscriptvalue_cast<QSqlQuery>(context->thisObject().data());
    int i = context->argument(0).toNumber();
    if (query.at() == i || query.seek(i)) { // Qt 4.6 doesn't optimize seek(at())
        QSqlRecord r = query.record();
        QScriptValue row = engine->newObject();
        for (int j=0; j<r.count(); ++j) {
            row.setProperty(r.fieldName(j), QScriptValue(engine,r.value(j).toString()));
        }
        return row;
    }
    return engine->undefinedValue();
}
コード例 #20
0
Row *TablePrivate::appendRow()
{
    Q_Q(Table);
    int index = q->rowCount();

    if(!q->insertRecord(-1,q->record()))
        return 0;

    QSqlQuery query = q->query();
    query.seek(index);
    int id = query.lastInsertId().toInt();
    Row *row = new Row(index, id, q);
    rows.append(row);
    rowsById.insert(id, row);
    return row;
}
コード例 #21
0
ファイル: execut_window.cpp プロジェクト: xuezeao/git_program
void Execut_window::searchPositionInfo(QString name,int i)//获取对应抽屉内的试剂rowid
{
    QSqlQuery query;
    int temporaryC = 0;
    query.exec(QString("select * from %1 where drawerNo=%2").arg(name).arg(saveDrawer[i]));


    query.last();
    temporaryC= query.at()+1;//at 0开始

    for(int i = 0; i < temporaryC ;i++)
    {
        query.seek(i);
        saveRowid[0] = i+1;
        saveRowid[i+1] = query.value(0).toInt();
    }
}
コード例 #22
0
ファイル: lookupcoursedialog.cpp プロジェクト: cschccc/tcp
void LookupCourseDialog::populateCourseTable()
{
	QSqlQuery query;
	QVector<QTableWidgetItem *> tableItems;

	courseTable->clearContents();
	courseTable->setRowCount(0);
	instructionLabel->hide();
	
	if (courseNameLineEdit->text().length() == 0)
		return;

	query.exec("select distinct cid, course_name from course_info where course_name like '%" 
		+ courseNameLineEdit->text() + "%' or cid like '%" 
		+ courseNameLineEdit->text() + "%' order by course_name");

	if (query.next()) {
		instructionLabel->setText("<font color='red'>" + tr("Double click on a course to add it to your course list.") + "</font>");
		instructionLabel->show();
		query.seek(-1);
	}
	else {
		instructionLabel->setText("<font color='red'>" + tr("No results. Please check your spelling.") + "</font>");
		instructionLabel->show();
		return;
	}

	int itemCount = 0;
	while (query.next()) {
		QTableWidgetItem *courseNumber = new QTableWidgetItem(query.value(0).toString());
		QTableWidgetItem *courseName = new QTableWidgetItem(query.value(1).toString());
		tableItems.push_back(courseNumber);
		tableItems.push_back(courseName);
		itemCount += 2;
	}
	
	const int NCOLUMNS = 2;
	int rowCount = itemCount / NCOLUMNS;
	
	courseTable->setRowCount(rowCount);

	int index = 0;
	for (int i = 0; i < rowCount; i++)
		for (int j = 0; j < NCOLUMNS; j++)
			courseTable->setItem(i, j, tableItems.at(index++));
}
コード例 #23
0
ファイル: FiGroupWidget.cpp プロジェクト: loh-tar/filu
void FiGroupWidget::groupUp()
{
  QSqlQuery* query = mFilu->getGroups(-1); // Get all groups
  if(!query)
  {
    // Absolutly no groups. Make a 'reset'.
    mMotherId = 0;
    mCurrendGroupId = 0;
    mMotherName->setText("");
    return;
  }

  // query looks like
  // group_id, name, mothergroup_id
  while(query->next())
  {
    // Search mother
    if(query->value(0).toInt() == mMotherId) break;
  }

  // Check if found. Could happens when group was deleted meanwhile.
  mMotherId = 0;
  mMotherName->setText("");
  QString actGroup;
  if(query->isValid())
  {
    actGroup  = query->value(1).toString();
    mMotherId = query->value(2).toInt();
  }

  if(mMotherId)
  {
    query->seek(-1);
    while(query->next())
    {
      // Search grandmother
      if(query->value(0).toInt() == mMotherId) break;
    }
    mMotherName->setText(query->value(1).toString());
  }

  getGroups();
  setActiveGroup(actGroup);
}
コード例 #24
0
ファイル: OrderAdapter.cpp プロジェクト: julianandreou/pos
boost::optional<int> OrderAdapter::getOrderIdByModelIndex(const QModelIndex& modelIndex) const
{
	boost::optional<int> orderId;

	QModelIndex index = modelIndex;

	if (index.isValid())
	{
		//! TODO - actually query model (instead of duplicating + assumption)
		QSqlQuery query;
		query.prepare("SELECT id FROM bike ORDER BY id ASC;");
		query.exec();

		query.seek(index.row());
		orderId = query.value(0).toInt();
	}

	return orderId;
}
コード例 #25
0
ファイル: itemmodel.cpp プロジェクト: ArtemHodeev/Gidrolog
void ItemModel::updateItems()
{
    QSqlQuery *query = new QSqlQuery(DatabaseAccessor::getDb());

    QString sql = QString("UPDATE item ");
    sql += ("SET name = :name, type_id = :type_id, min_value = :min_value, error_line = :error_line, display = :display ");
    sql += ("WHERE id = :id");
    query->prepare(sql);
    unsigned int i_id = 0;

    while(!items_to_update.isEmpty())
    {
        // Определение id параметра пробы
        // Если параметр пробы был уже БД и система знает его id
        if (items_to_update.first()->getId() > 0)
        {
            i_id = items_to_update.first()->getId();
        }
        //Если параметр пробы, был недавно добавлен и его редактировали
        else
        {
            QSqlQuery *q = new QSqlQuery(DatabaseAccessor::getDb());
            q->prepare("SELECT id FROM item");
            q->exec();
            q->seek(items_to_update.first()->getPosition());
            i_id = q->value("id").toUInt();
        }

        query->bindValue(":id", i_id);
        query->bindValue(":name", items_to_update.first()->getName());
        query->bindValue(":type_id", items_to_update.first()->getTypeId());
        query->bindValue(":min_value", items_to_update.first()->getMinValue());
        query->bindValue(":error_line",items_to_update.first()->getErrorLine());
        query->bindValue(":display", items_to_update.first()->getDisplay());
        query->exec();

        items_to_update.removeFirst();
    }
    qDebug()<<"Size of list_to_save at the end: " <<items_to_update.size();
    delete query;
}
コード例 #26
0
QSharedPointer<CompositeFood>
  MySQLBackEnd::createCompositeFoodFromQueryResults
    (QSqlQuery& query)
{
  QSharedPointer<CompositeFoodImpl> food_impl;

  if (query.first()) {

    const QSqlRecord& record = query.record();
    int id = record.field("Composite_Id").value().toInt();

    food_impl = QSharedPointer<CompositeFoodImpl>
      (new CompositeFoodImpl(id,
                             record.field("Description").value().toString(),
                             record.field("User_Id").value().toInt(),
                             record.field("Weight_g").value().toDouble(),
                             record.field("Volume_floz").value().toDouble(),
                             record.field("Quantity").value().toDouble(),
                             record.field("Servings").value().toDouble(),
                             record.field("CreationDate").value().toDate(),
                             record.field("ExpiryDate").value().toDate(),
                             record.field("IsNonce").value().toBool()));

    DataCache<CompositeFood>::getInstance().insert(id, food_impl);
  }

  if (food_impl && query.isActive()) {
    query.seek(-1); // Reset to before first record
    food_impl->setComponents
      (createComponentsFromQueryResults
         (query, food_impl, "CompositeLink_Id", "IntrafoodOrder"));
    if (food_impl->needsToBeReSaved()) {
      food_impl->saveToDatabase();
    }
  }

  return food_impl;
}
コード例 #27
0
ファイル: mainwindow.cpp プロジェクト: firephoenix/wmanual
void MainWindow::menuTreeClick(QModelIndex)
{
    QVariant clickedItem = menuTree->selectionModel()->currentIndex().data(Qt::UserRole);
    int rowId = menuTree->selectionModel()->currentIndex().row()+1;
    QSqlQuery rowQuery;
    switch(clickedItem.toInt())
    {
    case 1:
        {
            if(rowQuery.exec("SELECT tableid, adid FROM firstmenus WHERE id = "+QString().setNum(rowId)))
            {
                int adNumRows = 0;//定义搜索返回的行数
                if(db.driver()->hasFeature(QSqlDriver::QuerySize))//判断驱动是否包含QuerySize
                {
                    adNumRows = rowQuery.size();//将返回的行数赋于adNumRows
                }
                else
                {
                    rowQuery.last();//移至最后一行
                    adNumRows = rowQuery.at()+1;//将返回的行数赋于adNumRows
                    rowQuery.seek(-1);//返回第一行
                }
                if(adNumRows>0)//判断是否大于0
                {
                    rowQuery.next();
                    if(rowQuery.value(0).toInt()==0)
                    {
                        if(this->adView->isHidden())
                        {
                            this->rightSplitter->hide();
                            this->adView->show();
                        }
                        this->readAd(rowQuery.value(1).toInt());
                        this->adView->viewUpdate();
                    }
                    else
                    {
                        if(this->rightSplitter->isHidden())
                        {
                            this->adView->hide();
                            this->rightSplitter->show();
                        }
                        this->readTable(rowQuery.value(0).toInt());
                    }
                }
            }            
        }
        break;

    case 2:
        {
            if(rowQuery.exec("SELECT tableid, adid FROM secondmenus WHERE id = "+QString().setNum(rowId)))
            {
                int adNumRows = 0;//定义搜索返回的行数
                if(db.driver()->hasFeature(QSqlDriver::QuerySize))//判断驱动是否包含QuerySize
                {
                    adNumRows = rowQuery.size();//将返回的行数赋于adNumRows
                }
                else
                {
                    rowQuery.last();//移至最后一行
                    adNumRows = rowQuery.at()+1;//将返回的行数赋于adNumRows
                    rowQuery.seek(-1);//返回第一行
                }
                if(adNumRows>0)//判断是否大于0
                {
                    rowQuery.next();
                    if(rowQuery.value(0).toInt()==0)
                    {
                        if(this->adView->isHidden())
                        {
                            this->rightSplitter->hide();
                            this->adView->show();
                        }
                        this->readAd(rowQuery.value(1).toInt());
                        this->adView->viewUpdate();
                    }
                    else
                    {
                        if(this->rightSplitter->isHidden())
                        {
                            this->adView->hide();
                            this->rightSplitter->show();
                        }
                        this->readTable(rowQuery.value(0).toInt());
                    }
                }
            }
        }
        break;

    case 3:
        {
            if(rowQuery.exec("SELECT tableid, adid FROM thirdmenus WHERE id = "+QString().setNum(rowId)))
            {
                int adNumRows = 0;//定义搜索返回的行数
                if(db.driver()->hasFeature(QSqlDriver::QuerySize))//判断驱动是否包含QuerySize
                {
                    adNumRows = rowQuery.size();//将返回的行数赋于adNumRows
                }
                else
                {
                    rowQuery.last();//移至最后一行
                    adNumRows = rowQuery.at()+1;//将返回的行数赋于adNumRows
                    rowQuery.seek(-1);//返回第一行
                }
                if(adNumRows>0)//判断是否大于0
                {
                    rowQuery.next();
                    if(rowQuery.value(0).toInt()==0)
                    {
                        if(this->adView->isHidden())
                        {
                            this->rightSplitter->hide();
                            this->adView->show();
                        }
                        this->readAd(rowQuery.value(1).toInt());
                        this->adView->viewUpdate();
                    }
                    else
                    {
                        if(this->rightSplitter->isHidden())
                        {
                            this->adView->hide();
                            this->rightSplitter->show();
                        }
                        this->readTable(rowQuery.value(0).toInt());
                    }
                }
            }
        }
        break;

    default:
        break;
    }
}
コード例 #28
0
ファイル: mainwindow.cpp プロジェクト: firephoenix/wmanual
//创建目录树
void MainWindow::createMenuTree()
{
    QSqlQuery fstMenuQuery;//对firstmenus搜索
    QSqlQuery secMenuQuery;//对secondmenus搜索
    QSqlQuery thdMenuQuery;//对thirdmenus搜索
    if(fstMenuQuery.exec("SELECT menuitem, id FROM firstmenus;"))//判断搜索数据库中一级目录
    {
        int fstNumRows = 0;//定义搜索返回的行数
        if(db.driver()->hasFeature(QSqlDriver::QuerySize))//判断驱动是否包含QuerySize
        {
            fstNumRows = fstMenuQuery.size();//将返回的行数赋于fstNumRows
        }
        else
        {
            fstMenuQuery.last();//移至最后一行
            fstNumRows = fstMenuQuery.at()+1;//将返回的行数赋于fstNumRows
            fstMenuQuery.seek(-1);//返回第一行
        }
        if(fstNumRows>0)//判断搜索得到的结果是否大于0
        {
            menuTree = new QTreeView();//建立目录树
            treeModel = new QStandardItemModel(fstNumRows,1);//设置目录的大小
            treeModel->setHeaderData(0,Qt::Horizontal,tr("目录"));//设置目录头
            int fstInt = 0;
            while(fstMenuQuery.next())//加载一级目录
            {
                QStandardItem *fstItem = new QStandardItem(fstMenuQuery.value(0).toString());//新建一级目录各子项
                fstItem->setData(1,Qt::UserRole);//设置目录阶数
                treeModel->setItem(fstInt,fstItem);//将一级目录加载到目录树中
                fstInt++;//fstInt自加

                if(secMenuQuery.exec("SELECT menuitem, id FROM secondmenus WHERE parentid = "+ fstMenuQuery.value(1).toString()))//判断是否有二级目录
                {
                    int secNumRows = 0;//定义搜索返回的行数
                    if(db.driver()->hasFeature(QSqlDriver::QuerySize))
                    {
                        secNumRows = secMenuQuery.size();
                    }
                    else
                    {
                        secMenuQuery.last();
                        secNumRows = secMenuQuery.at()+1;
                        secMenuQuery.seek(-1);
                    }
                    if(secNumRows>0)//判断搜索得到的结果是否大于0
                    {
                        while(secMenuQuery.next())//加载二级目录
                        {
                            QStandardItem *secItem = new QStandardItem(secMenuQuery.value(0).toString());//新建二级目录各子项
                            secItem->setData(2,Qt::UserRole);//设置目录阶数为2
                            fstItem->appendRow(secItem);//加载二级目录

                            if(thdMenuQuery.exec("SELECT menuitem, id FROM thirdmenus WHERE parentid = "+ secMenuQuery.value(1).toString()))
                            {
                                int thdNumRows = 0;
                                if(db.driver()->hasFeature(QSqlDriver::QuerySize))
                                {
                                    thdNumRows = thdMenuQuery.size();
                                }
                                else
                                {
                                    thdMenuQuery.last();
                                    thdNumRows = thdMenuQuery.at()+1;
                                    thdMenuQuery.seek(-1);
                                }
                                if(thdNumRows>0)
                                {
                                    while(thdMenuQuery.next())//加载三级目录
                                    {
                                        QStandardItem *thdItem = new QStandardItem(thdMenuQuery.value(0).toString());//新建三级目录各子项
                                        thdItem->setData(3,Qt::UserRole);//设置目录阶数为3
                                        secItem->appendRow(thdItem);//加载三级目录
                                    }
                                }
                            }
                        }
                    }
                }
            }
            menuTree->setModel(treeModel);//设置目录树的MODEL
            menuTree->setEditTriggers(QAbstractItemView::NoEditTriggers);//设置为不可编辑
            menuTree->resizeColumnToContents(0);//设置树的宽度
            mainSplitter->addWidget(menuTree);//将目录加载到主面板中

            connect(menuTree,SIGNAL(clicked(QModelIndex)),this,SLOT(menuTreeClick(QModelIndex)));//当用户点击树目录时,启动menuTreeClick函数
        }
    }
}
コード例 #29
0
void MainWindow::realtimeDataSlot(){



       double flowrate,voltage,irvalue,timestamp,relaystate;
       QString dev_name;

       // assign the appropriate driver to the database
       QSqlDatabase  db_plot = QSqlDatabase::addDatabase("QSQLITE");

       // open the specified database
        db_plot.setDatabaseName("/home/uday/Desktop/Project2/data.db");


        if(!db_plot.open()){
             qDebug("Failed to open the database");
        }
        else{
            // qDebug("Connected to the database");

        /* order the querries ordered by timestamp and compare previous last row with current_last row
         * select the querries greater than previous timestamp and
         * add the data to the graph corresponding to the device
         **/

        QString stmt =QString("SELECT  Flowrate, Voltage, IR_sensor, RelayState, DeviceID,Timestamp FROM DATA ORDER BY Timestamp;");
       // qDebug() <<"Query:"<< stmt;
        QSqlQuery query;
        query.prepare(stmt);

        if( !query.exec() ){
            qDebug() << query.lastError();
        }
        else{
           qDebug( "Qeury: Executed successfully" );
          }
        //count the current number of rows in database ordered by timestamp
        int  cur_last_row;

        if(query.last())   cur_last_row = query.at();

        qDebug()<<"current last row: "<<cur_last_row;

        if(cur_last_row >= prev_last_row) {

                     /*Before adding data, check to see if new devices are added
                      * and add a curve for the device
                      **/

                     // if db is not specified, then default database of this program is choosen
                     QSqlQuery dev_query("SELECT  DISTINCT DeviceID FROM DATA ORDER BY Timestamp;");
                     if( !dev_query.exec() )
                       qDebug() << dev_query.lastError();
                     else{
                       qDebug( "Qeury executed successfully" );
                     }

                     // find the number of distinct devices
                      int cur_num_dev;
                      if(dev_query.last())   cur_num_dev = dev_query.at() ;// dev_num counts from "zero"

                     //qDebug() << "number of distinct devices: " << cur_num_dev;


                     if(cur_num_dev>=num_dev){

                         for(int i=num_dev; i<cur_num_dev+1; i++){
                              dev_query.seek(i);
                              dev_id[i]=dev_query.value(0).toString();
                              qDebug() << dev_id[i];
                             // add the add_graph function
                             // addCurve(ui->qtplot,i);
                              addCurve(ui->qtplot_2,i);
                              addCurve(ui->qtplot_3,i);
                         }
                         num_dev=cur_num_dev+1;
                      }

                       query.seek(prev_last_row);
                       flowrate=query.value(0).toDouble();//flowrate,voltage,irvalue,timestamp,relaystate
                       voltage=query.value(1).toDouble();
                       irvalue=query.value(2).toDouble();
                       relaystate=query.value(3).toDouble();
                       timestamp=query.value(5).toDouble();
                      // qDebug()<<flowrate<<voltage<<irvalue<<relaystate<< timestamp;

                       dev_name=query.value(4).toString();
                      //  qDebug()<<dev_name;
                       // add the current data to the corresponding curve
                       //addData(ui->qtplot,dev_name,timestamp,flowrate);
                       addData(ui->qtplot_2,dev_name,timestamp,voltage);
                       addData(ui->qtplot_3,dev_name, timestamp,irvalue);

                     //  if(relaystate==0)  {ui->on->setStyleSheet("background-color:  #D1CCCC");
                    //   ui->off->setStyleSheet("background-color: red");}
                     //  if(relaystate==1)  {ui->on->setStyleSheet("background-color: red");
                      // ui->off->setStyleSheet("background-color:  #D1CCCC");}


                       prev_last_row +=1;
                     //  qDebug()<<"previous last row: "<<prev_last_row;
           }

     }//if connected to the database
  db_plot.close();
}
コード例 #30
0
ファイル: historykeeper.cpp プロジェクト: codedust/qTox
HistoryKeeper::HistoryKeeper(GenericDdInterface *db_) :
    db(db_)
{
    /*
     DB format
     chats:
      * name -> id map
       id      -- auto-incrementing number
       name    -- chat's name (for user to user conversation it is opposite user public key)
       ctype   -- chat type, reserved for group chats

     aliases:
      * user_id -> id map
       id       -- auto-incrementing number
       user_id  -- user's public key
       av_hash  -- hash of user's avatar
       avatar   -- user's avatar

     history:
       id           -- auto-incrementing number
       timestamp
       chat_id      -- current chat ID (resolves from chats table)
       sender       -- sender's ID (resolves from aliases table)
       message
       alias        -- sender's alias in
    */

    // for old tables:
    QSqlQuery ans = db->exec("SELECT seq FROM sqlite_sequence WHERE name=\"history\";");
    if (ans.first())
    {
        int idMax = ans.value(0).toInt();
        QSqlQuery ret = db->exec("SELECT seq FROM sqlite_sequence WHERE name=\"sent_status\";");
        int idCur = 0;
        if (ret.first())
            idCur = ret.value(0).toInt();

        if (idCur != idMax)
        {
            QString cmd = QString("INSERT INTO sent_status (id, status) VALUES (%1, 1);").arg(idMax);
            db->exec(cmd);
        }
    }
    //check table stuct
    ans = db->exec("PRAGMA table_info (\"history\")");
    ans.seek(5);
    if (!ans.value(1).toString().contains("alias"))
    {
        //add collum in table
        db->exec("ALTER TABLE history ADD COLUMN alias TEXT");
        qDebug() << "Struct DB updated: Added column alias in table history.";
    }

    ans.clear();
    ans = db->exec("PRAGMA table_info('aliases')");
    ans.seek(2);
    if (!ans.value(1).toString().contains("av_hash"))
    {
        //add collum in table
        db->exec("ALTER TABLE aliases ADD COLUMN av_hash BLOB");
        qDebug() << "Struct DB updated: Added column av_hash in table aliases.";
    }

    ans.seek(3);
    if (!ans.value(1).toString().contains("avatar"))
    {
        //add collum in table
        needImport = true;
        db->exec("ALTER TABLE aliases ADD COLUMN avatar BLOB");
        qDebug() << "Struct DB updated: Added column avatar in table aliases.";
    }

    updateChatsID();
    updateAliases();

    setSyncType(Settings::getInstance().getDbSyncType());

    messageID = 0;
    QSqlQuery sqlAnswer = db->exec("SELECT seq FROM sqlite_sequence WHERE name=\"history\";");
    if (sqlAnswer.first())
        messageID = sqlAnswer.value(0).toLongLong();
}