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


C++ QSqlRecord::count方法代码示例

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


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

示例1: selectRow

/*!
    \since 5.0

    Refreshes \a row in the model with values from the database table row matching
    on primary key values. Without a primary key, all column values must match. If
    no matching row is found, the model will show an empty row.

    Returns \c true if successful; otherwise returns \c false.

    \sa select()
*/
bool QSqlTableModel::selectRow(int row)
{
    Q_D(QSqlTableModel);

    if (row < 0 || row >= rowCount())
        return false;

    const int table_sort_col = d->sortColumn;
    d->sortColumn = -1;
    const QString table_filter = d->filter;
    d->filter = d->db.driver()->sqlStatement(QSqlDriver::WhereStatement,
                                              d->tableName,
                                              primaryValues(row),
                                              false);
    static const QString wh = Sql::where() + Sql::sp();
    if (d->filter.startsWith(wh, Qt::CaseInsensitive))
        d->filter.remove(0, wh.length());

    QString stmt;

    if (!d->filter.isEmpty())
        stmt = selectStatement();

    d->sortColumn = table_sort_col;
    d->filter = table_filter;

    if (stmt.isEmpty())
        return false;

    bool exists;
    QSqlRecord newValues;

    {
        QSqlQuery q(d->db);
        q.setForwardOnly(true);
        if (!q.exec(stmt))
            return false;

        exists = q.next();
        newValues = q.record();
    }

    bool needsAddingToCache = !exists || d->cache.contains(row);

    if (!needsAddingToCache) {
        const QSqlRecord curValues = record(row);
        needsAddingToCache = curValues.count() != newValues.count();
        if (!needsAddingToCache) {
            // Look for changed values. Primary key fields are customarily first
            // and probably change less often than other fields, so start at the end.
            for (int f = curValues.count() - 1; f >= 0; --f) {
                if (curValues.value(f) != newValues.value(f)) {
                    needsAddingToCache = true;
                    break;
                }
            }
        }
    }

    if (needsAddingToCache) {
        d->cache[row].refresh(exists, newValues);
        emit headerDataChanged(Qt::Vertical, row, row);
        emit dataChanged(createIndex(row, 0), createIndex(row, columnCount() - 1));
    }

    return true;
}
开发者ID:OniLink,项目名称:Qt5-Rehost,代码行数:78,代码来源:qsqltablemodel.cpp

示例2: if

// loadFields() gets the type from the field record
void QgsDb2Provider::loadFields()
{
  mAttributeFields.clear();
  //mDefaultValues.clear();
  QString table = QString( "%1.%2" ).arg( mSchemaName, mTableName );

  // Use the Qt functionality to get the fields and their definitions.
  QSqlRecord r = mDatabase.record( table );
  int fieldCount = r.count();

  for ( int i = 0; i < fieldCount; i++ )
  {
    QSqlField f = r.field( i );
    int typeID = f.typeID(); // seems to be DB2 numeric type id (standard?)
    QString sqlTypeName = db2TypeName( typeID );
    QVariant::Type sqlType = f.type();
    QgsDebugMsg( QString( "name: %1; length: %2; sqlTypeID: %3; sqlTypeName: %4" )
                 .arg( f.name() ).arg( f.length() ).arg( QString::number( typeID ), sqlTypeName ) );
    if ( f.name() == mGeometryColName ) continue; // Got this with uri, just skip
    if ( sqlType == QVariant::String )
    {
      mAttributeFields.append(
        QgsField(
          f.name(),
          sqlType,
          sqlTypeName,
          f.length()
        ) );
    }
    else if ( sqlType == QVariant::Double )
    {
      mAttributeFields.append(
        QgsField(
          f.name(),
          sqlType,
          sqlTypeName,
          f.length(),
          f.precision()
        ) );
    }
    else
    {
      mAttributeFields.append(
        QgsField(
          f.name(),
          sqlType,
          sqlTypeName
        ) );
    }

    if ( !f.defaultValue().isNull() )
    {
      mDefaultValues.insert( i, f.defaultValue() );
    }
// Hack to get primary key since the primaryIndex function above doesn't work
// on z/OS. Pick first integer column.
    if ( mFidColName.length() == 0 &&
         ( sqlType == QVariant::LongLong || sqlType == QVariant::Int ) )
    {
      mFidColName = f.name();
    }
  }
}
开发者ID:mterente,项目名称:QGIS,代码行数:64,代码来源:qgsdb2provider.cpp

示例3: save

bool SqlDbBackend::save( Object *object )
{
	assert( object );
	bool update;
	QSqlRecord *record;
	QSqlCursor cursor( object->classInfo()->name() );

	if ( object->oid() == 0 ) {
		object->setOid( newOid() );
		cursor.select();
		record = cursor.primeInsert();
		update = false;
	} else {
		cursor.select( "to_number( " + oidFieldName() + ", '9999999999G0') = " + oidToString( object->oid() ) );
		if ( ! cursor.next() ) {
			cursor.select();
			record = cursor.primeInsert();
			update = false;
		} else {
			record = cursor.primeUpdate();
			update = true;
		}
	}

	// We don't mark any field as generated. So at first, none
	// would be included in the INSERT/UPDATE. Then we must make sure
	// we set the generated flag to each property field.
	// Note that this is necesary as we want relation fields to take their
	// default values when inserted.
	for ( uint i = 0; i < record->count(); ++i ) {
		record->setGenerated( i, false );
	}

	record->setValue( oidFieldName(), object->oid() );
	record->setGenerated( oidFieldName(), true );
	record->setValue( sequenceFieldName(), newSeq() );
	record->setGenerated( sequenceFieldName(), true );

	PropertiesIterator pIt( object->propertiesBegin() );
	PropertiesIterator pEnd( object->propertiesEnd() );
	Property prop;
	for ( ; pIt != pEnd; ++pIt ) {
		prop = pIt.data();
		if ( prop.readOnly() || ! record->contains( prop.name() ) )
			continue;

		if ( prop.type() == QVariant::Pixmap ) {
			QByteArray img;
			QBuffer buffer( img );
			buffer.open( IO_WriteOnly );
			prop.value().toPixmap().save( &buffer, "PNG" );
			record->setValue( prop.name(), img );
//		} else if( prop.type() == QVariant::List ){
//			QByteArray pin;
//			QDataStream stream( pin, IO_ReadWrite );
//			stream << prop.value();
//			record->setValue( prop.name(), stream );
		} else {
			record->setValue( prop.name(), prop.value() );
		}
		record->setGenerated( prop.name(), true );
	}

	if ( update ) {
		if (! cursor.update() ) {
			kdDebug() << k_funcinfo << " -> " << cursor.lastError().text() << endl;
			kdDebug() << k_funcinfo << " -> " << cursor.executedQuery() << endl;
			ERROR( "Update failed" );
		}
	} else {
		if ( ! cursor.insert() ) {
			kdDebug() << k_funcinfo << " -> " << cursor.lastError().text() << endl;
			kdDebug() << k_funcinfo << " -> " << cursor.executedQuery() << endl;
			ERROR( "Insert failed" );
		}
	}
	return true;
}
开发者ID:BackupTheBerlios,项目名称:kandau-svn,代码行数:78,代码来源:sqldbbackend.cpp

示例4: fetchNext

bool SQLiteResultPrivate::fetchNext(SqlCachedResult::ValueCache &values, int idx, bool initialFetch)
{
    int res;
    int i;

    if (skipRow) {
        // already fetched
        Q_ASSERT(!initialFetch);
        skipRow = false;
        for(int i=0;i<firstRow.count();i++)
            values[i]=firstRow[i];
        return skippedStatus;
    }
    skipRow = initialFetch;

    if(initialFetch) {
        firstRow.clear();
        firstRow.resize(sqlite3_column_count(stmt));
    }

    if (!stmt) {
        q->setLastError(QSqlError(QCoreApplication::translate("SQLiteResult", "Unable to fetch row"),
                                  QCoreApplication::translate("SQLiteResult", "No query"), QSqlError::ConnectionError));
        q->setAt(QSql::AfterLastRow);
        return false;
    }
    res = sqlite3_step(stmt);

    switch(res) {
    case SQLITE_ROW:
        // check to see if should fill out columns
        if (rInf.isEmpty())
            // must be first call.
            initColumns(false);
        if (idx < 0 && !initialFetch)
            return true;
        for (i = 0; i < rInf.count(); ++i) {
            switch (sqlite3_column_type(stmt, i)) {
            case SQLITE_BLOB:
                values[i + idx] = QByteArray(static_cast<const char *>(
                            sqlite3_column_blob(stmt, i)),
                            sqlite3_column_bytes(stmt, i));
                break;
            case SQLITE_INTEGER:
                values[i + idx] = sqlite3_column_int64(stmt, i);
                break;
            case SQLITE_FLOAT:
                switch(q->numericalPrecisionPolicy()) {
                    case QSql::LowPrecisionInt32:
                        values[i + idx] = sqlite3_column_int(stmt, i);
                        break;
                    case QSql::LowPrecisionInt64:
                        values[i + idx] = sqlite3_column_int64(stmt, i);
                        break;
                    case QSql::LowPrecisionDouble:
                    case QSql::HighPrecision:
                    default:
                        values[i + idx] = sqlite3_column_double(stmt, i);
                        break;
                };
                break;
            case SQLITE_NULL:
                values[i + idx] = QVariant(QVariant::String);
                break;
            default:
                values[i + idx] = QString(reinterpret_cast<const QChar *>(
                            sqlite3_column_text16(stmt, i)),
                            sqlite3_column_bytes16(stmt, i) / sizeof(QChar));
                break;
            }
        }
        return true;
    case SQLITE_DONE:
        if (rInf.isEmpty())
            // must be first call.
            initColumns(true);
        q->setAt(QSql::AfterLastRow);
        sqlite3_reset(stmt);
        return false;
    case SQLITE_CONSTRAINT:
    case SQLITE_ERROR:
        // SQLITE_ERROR is a generic error code and we must call sqlite3_reset()
        // to get the specific error message.
        res = sqlite3_reset(stmt);
        q->setLastError(qMakeError(access, QCoreApplication::translate("SQLiteResult",
                        "Unable to fetch row"), QSqlError::ConnectionError, res));
        q->setAt(QSql::AfterLastRow);
        return false;
    case SQLITE_MISUSE:
    case SQLITE_BUSY:
    default:
        // something wrong, don't get col info, but still return false
        q->setLastError(qMakeError(access, QCoreApplication::translate("SQLiteResult",
                        "Unable to fetch row"), QSqlError::ConnectionError, res));
        sqlite3_reset(stmt);
        q->setAt(QSql::AfterLastRow);
        return false;
    }
    return false;
}
开发者ID:Helgion,项目名称:quiterss,代码行数:100,代码来源:sqlitedriver.cpp

示例5: postRow

bool SqlTableModel::postRow(int row_no, bool throw_exc)
{
	qfLogFuncFrame() << row_no;

	QF_ASSERT(m_table.isValidRowIndex(row_no),
			  QString("row: %1 is out of range of rows (%2)").arg(row_no).arg(m_table.rowCount()),
			  return false);
	qfu::TableRow &row_ref = m_table.rowRef(row_no);
	bool ret = true;
	if(row_ref.isInsert()) {
		qfDebug() << "\tINSERT";

		//QSet<QString> referenced_foreign_tables = referencedForeignTables();
		//int tbl_cnt = 0;
		qf::core::sql::Connection sql_conn = sqlConnection();
		QSqlDriver *sqldrv = sql_conn.driver();
		const QStringList table_ids = tableIdsSortedAccordingToForeignKeys();
		for(QString table_id : table_ids) {
			qfDebug() << "\ttable:" << table_id;
			QSqlRecord rec;
			int i = -1;
			int serial_ix = -1;
			bool serial_ix_explicitly_set = false;
			int primary_ix = -1;
			//QSqlIndex pri_ix = ti.primaryIndex();
			//bool has_blob_field = false;
			Q_FOREACH(const qf::core::utils::Table::Field &fld, row_ref.fields()) {
				i++;
				if(fld.tableId() != table_id)
					continue;
				//qfInfo() << table_id << "field:" << fld.name() << "is serial:" << fld.isSerial();
				bool is_field_dirty = row_ref.isDirty(i);
				if(fld.isSerial()) {
					/// always include serial fields, an empty line cannot be inserted in other case
					//is_field_dirty = true;
					serial_ix = i;
					serial_ix_explicitly_set = is_field_dirty;
					qfDebug() << "\t serial ix:" << serial_ix;
				}
				if(fld.isPriKey()) {
					/// always include prikey field, an empty line cannot be inserted in other case
					//is_field_dirty = true;
					primary_ix = i;
					qfDebug() << "\t primary ix:" << primary_ix;
				}
				if(!is_field_dirty)
					continue;
				qfDebug() << "\tdirty field:" << fld.name();
				QVariant v = row_ref.value(i);
				if(is_field_dirty) {
					/// null hodnotu nema smysl insertovat, pokud to neni nutne kvuli necemu jinemu
					/// naopak se pri insertu dokumentu z vice join tabulek muze stat, ze se vlozi to not-null fieldu null hodnota
					/// pokud je insert, join radek neexistuje, takze hodnoty jsou null a mysql v takovem pripade v resultsetu nastavi
					/// i not-null field na nullable
					QSqlField new_fld;
					//if(v.isNull() && fld.isSerial())
					//	v = 0;
					new_fld.setValue(v);
					//qfInfo() << "\t\t" << "val type:" << QVariant::typeToName(f.value().type());
					new_fld.setName(fld.shortName());
					rec.append(new_fld);
				}
			}

			qfDebug() << "updating table inserts" << table_id;
			QString qs;
			QString table = sql_conn.fullTableNameToQtDriverTableName(table_id);
			qfs::Query q(sql_conn);
			if(rec.isEmpty()) {
				if(serial_ix >= 0) {
					qs = "INSERT INTO %1 DEFAULT VALUES";
					qs = qs.arg(table);
				}
			}
			else {
				qs = sqldrv->sqlStatement(QSqlDriver::InsertStatement, table, rec, true);
				//qs = fixSerialDefaultValue(qs, serial_ix, rec);
			}
			if(qs.isEmpty())
				continue;
			qfDebug() << "\texecuting prepared query:" << qs;
			bool ok = q.prepare(qs);
			if(!ok) {
				qfError() << "Cannot prepare query:" << qs;
			}
			else {
				for(int i=0; i<rec.count(); i++) {
					QVariant::Type type = rec.field(i).value().type();
					//qfInfo() << "\t" << rec.field(i).name() << "bound type:" << QVariant::typeToName(type);
					qfDebug() << "\t\t" << rec.field(i).name() << "bound type:" << QVariant::typeToName(type) << "value:" << rec.field(i).value().toString().mid(0, 100);
					q.addBindValue(rec.field(i).value());
				}
			}
			ok = q.exec();
			if(ok) {
				qfDebug() << "\tnum rows affected:" << q.numRowsAffected();
				int num_rows_affected = q.numRowsAffected();
				//setNumRowsAffected(q.numRowsAffected());
				QF_ASSERT(num_rows_affected == 1,
						  tr("numRowsAffected() = %1, should be 1\n%2").arg(num_rows_affected).arg(qs),
//.........这里部分代码省略.........
开发者ID:arnost00,项目名称:quickbox,代码行数:101,代码来源:sqltablemodel.cpp

示例6: describe

toQColumnDescriptionList mysqlQuery::describe(QSqlRecord record)
{
    ColumnDescriptions.clear();
    for (int i = 0; i < record.count(); i++)
    {
        toCache::ColumnDescription desc;
        desc.AlignRight = false;
        desc.Name = record.fieldName(i);
        int size = 1;
        QSqlField info = record.field(desc.Name);
        switch (info.typeID())
        {
        case FIELD_TYPE_DECIMAL:
            desc.Datatype = QString::fromLatin1("DECIMAL");
            break;
        case FIELD_TYPE_TINY:
            desc.Datatype = QString::fromLatin1("TINY");
            break;
        case FIELD_TYPE_SHORT:
            desc.Datatype = QString::fromLatin1("SHORT");
            break;
        case FIELD_TYPE_LONG:
            desc.Datatype = QString::fromLatin1("LONG");
            break;
        case FIELD_TYPE_FLOAT:
            desc.Datatype = QString::fromLatin1("FLOAT");
            break;
        case FIELD_TYPE_DOUBLE:
            desc.Datatype = QString::fromLatin1("DOUBLE");
            break;
        case FIELD_TYPE_NULL:
            desc.Datatype = QString::fromLatin1("NULL");
            break;
        case FIELD_TYPE_TIMESTAMP:
            desc.Datatype = QString::fromLatin1("TIMESTAMP");
            break;
        case FIELD_TYPE_LONGLONG:
            desc.Datatype = QString::fromLatin1("LONGLONG");
            break;
        case FIELD_TYPE_INT24:
            desc.Datatype = QString::fromLatin1("INT23");
            break;
        case FIELD_TYPE_DATE:
            desc.Datatype = QString::fromLatin1("DATE");
            break;
        case FIELD_TYPE_TIME:
            desc.Datatype = QString::fromLatin1("TIME");
            break;
        case FIELD_TYPE_DATETIME:
            desc.Datatype = QString::fromLatin1("DATETIME");
            break;
        case FIELD_TYPE_YEAR:
            desc.Datatype = QString::fromLatin1("YEAR");
            break;
        case FIELD_TYPE_NEWDATE:
            desc.Datatype = QString::fromLatin1("NEWDATE");
            break;
        case FIELD_TYPE_ENUM:
            desc.Datatype = QString::fromLatin1("ENUM");
            break;
        case FIELD_TYPE_SET:
            desc.Datatype = QString::fromLatin1("SET");
            break;
        case FIELD_TYPE_TINY_BLOB:
            desc.Datatype = QString::fromLatin1("TINY_BLOB");
            break;
        case FIELD_TYPE_MEDIUM_BLOB:
            desc.Datatype = QString::fromLatin1("MEDIUM_BLOB");
            break;
        case FIELD_TYPE_LONG_BLOB:
            desc.Datatype = QString::fromLatin1("LONG_BLOB");
            break;
        case FIELD_TYPE_BLOB:
            desc.Datatype = QString::fromLatin1("BLOB");
            break;
        case FIELD_TYPE_VAR_STRING:
            desc.Datatype = QString::fromLatin1("VAR_STRING");
            break;
        case FIELD_TYPE_STRING:
            desc.Datatype = QString::fromLatin1("STRING");
            break;
        default:
            desc.Datatype = QString::fromLatin1("UNKNOWN");
            break;
        }

        if (info.length() > size)
        {
            desc.Datatype += QString::fromLatin1(" (");
            if (info.length() % size == 0)
                desc.Datatype += QString::number(info.length() / size);
            else
                desc.Datatype += QString::number(info.length());
            if (info.precision() > 0)
            {
                desc.Datatype += QString::fromLatin1(",");
                desc.Datatype += QString::number(info.precision());
            }
            desc.Datatype += QString::fromLatin1(")");
        }
//.........这里部分代码省略.........
开发者ID:tora-tool,项目名称:tora,代码行数:101,代码来源:toqmysqlquery.cpp

示例7: execQuery

void MQLEdit::execQuery()
{
  if(!OpenRPT::loggedIn)
  {
    QMessageBox::warning(this, tr("Not Connected"),
                         tr("You must be connected to a database in order "
                            "to execute a query."));
    return;
  }

  _results->_table->setRowCount(0);
  _results->_table->setColumnCount(0);
  
  _sql->_log->clear();
  _log->_log->clear();
  _log->_log->append(tr("---- Parsing Query ----\n"));
  MetaSQLQuery mql(_text->toPlainText());
  _log->_log->append(mql.parseLog());
  if(mql.isValid())
  {
    _log->_log->append(tr("Query parsed."));
    _log->_log->append(tr("---- Executing Query ----"));
    ParameterList plist = _pEdit->getParameterList();

    if (toolsTest_ModeAction->isChecked())
      XSqlQuery begin("BEGIN;");

    XSqlQuery qry = mql.toQuery(plist);
    _sql->_log->append(qry.executedQuery());
    if(qry.isActive()) {
        QSqlRecord rec = qry.record();
        int ncols = rec.count();
        _results->_table->setColumnCount(ncols);
        int c;
        for(c = 0; c < ncols; c++)
          _results->_table->setHorizontalHeaderItem(c, new QTableWidgetItem(rec.fieldName(c)));
        int nrows = 0;
        while(qry.next())
        {
          _results->_table->setRowCount(nrows + 1);
          for(c = 0; c < ncols; c++)
            _results->_table->setItem(nrows, c, new QTableWidgetItem(qry.value(c).toString()));
          nrows++;
        }
        showResults();
    }
    else
    {
      _log->_log->append(tr("Failed to execute query."));
      QSqlError err = qry.lastError();
      _log->_log->append(err.text());
    }

    if (toolsTest_ModeAction->isChecked())
      XSqlQuery begin("ROLLBACK;");
  }
  else
  {
    _log->_log->append(tr("ERROR: Invalid query!"));
    showLog();
  }   
}
开发者ID:IlyaDiallo,项目名称:openrpt,代码行数:62,代码来源:mqledit.cpp

示例8: myquery

QPair<QString,QString> SafetBinaryRepo::dataJSON(const QString &nametable,
                                                 const QString& filter,
                                                 const QStringList& todatefields,
                                                 const QStringList& tospandatefields
                                                 ) {
    QPair<QString,QString> result;
    result.first = "safetlist =[\n";
    result.second = "safetcolumns = [\n";
    if (!_binaryDb.isOpen()) {
        SYE << tr("Repositorio Binario (search): la base de datos no est� abierta");
        return result;
    }
    QString strsql;

    QSqlQuery myquery(_binaryDb);

    if (filter.isEmpty()) {
        strsql = _templatesearchall.arg(nametable);
    }
    else {
        strsql = _templatesearch.arg(nametable).arg(filter);
    }


    bool executed = myquery.exec(strsql);

    if ( !executed ) {
        SYW << tr("...Repositorio Binario (JSON):"
                  "No se puede ejecutar la sentencia: \"%1\"")
               .arg(strsql);
        //_binaryDb.close();
        return result;
   }
   QSqlRecord rec = myquery.record();
   QDateTime mynow = QDateTime::currentDateTime();
   while(myquery.next() ) {
       result.first += "\n{";
       for (int i= 0; i< rec.count(); i++){
           QString fieldname = rec.fieldName(i).trimmed();
           QString value = myquery.value(i).toString().trimmed();
           if (todatefields.contains(fieldname)) {
               bool ok;
               uint seconds = value.toUInt(&ok);
               value = QDateTime::fromTime_t(seconds).toString("dd/MM/yyyy hh:mmap");
           }
           else if (tospandatefields.contains(fieldname) ) {
               bool ok;
               int days = 0;
               int seconds = value.toUInt(&ok);
               QString datestr = QDateTime::fromTime_t(mynow.toTime_t()-seconds).toString("dd/MM/yyyy hh:mmap");
               value = SafetWorkflow::humanizeDate(days,datestr,"dd/MM/yyyy hh:mmap",
                                                   mynow, SafetWorkflow::WaitTime);
           }

            result.first += QString("%1:\"%2\",")
                    .arg(fieldname)
                    .arg(value);
       }
       result.first.chop(1);
       result.first += "},\n";

   }
   result.first.chop(2);
   result.first += "\n];\n";



   // Nombre de campos
   for (int i= 0; i< rec.count(); i++){
        result.second += QString(
                "{ key:\"%1\",label:\"%1\","
                "width:%2,resizeable:true,sortable:true},\n")
                .arg(rec.fieldName(i).trimmed())
                .arg(SafetYAWL::getScriptLen(rec.field(i)));
   }

   result.second.chop(2);
   result.second += "\n];\n";


    return result;

}
开发者ID:Cenditel,项目名称:pysafet,代码行数:83,代码来源:SafetBinaryRepo.cpp

示例9: executeSql

void SQLDialog::executeSql(const QString& sqlString)
{
  QSqlDatabase& db = m_db.getDB();
  QSqlQuery query(db);
  if (!query.exec(sqlString))
  {
    m_statusBar->showMessage(query.lastError().text());
  }
  else
  {
    if (query.isSelect())
    {
      if (m_tableWidget == nullptr)
      {
        m_statusBar->showMessage(tr("Select not displayed because table widget is null"));
      }
      else
      {
        QSqlRecord rec = query.record();

        int numCols = rec.count();
        int numRows = query.size() + 1;

        m_tableWidget->clear();
        m_tableWidget->setColumnCount(numCols);
        m_tableWidget->setRowCount(numRows);

        QStringList fieldNames;
        int i;
        for (i=0; i<rec.count(); ++i)
        {
          fieldNames << rec.fieldName(i);
        }
        m_tableWidget->setHorizontalHeaderLabels(fieldNames);

        int row=0;
        while (query.isActive() && query.next())
        {
          for (int col=0; col<numCols; ++col)
          {
            QTableWidgetItem *newItem = new  QTableWidgetItem(query.value(col).toString());
            if (numRows <= row)
            {
              numRows = row + 1;
              m_tableWidget->setRowCount(numRows);
            }
            m_tableWidget->setItem(row, col, newItem);
          }
          ++row;
          //ScrollMessageBox::information(this, "Got a row!", QString("Have row %1 and size is %2").arg(row).arg(query.size()));
        }
        m_tableWidget->resizeColumnsToContents();
        m_statusBar->showMessage(QString(tr("Read %1 records")).arg(row));
      }
    }
    else
    {
      int numAffected = query.numRowsAffected();
      if (numAffected >= 0)
      {
        m_statusBar->showMessage(QString(tr("Successful query with %1 rows arrected")).arg(numAffected));
      }
      else
      {
        m_statusBar->showMessage(QString(tr("Successful query!")));
      }
    }
    // Handle things here!
  }
}
开发者ID:pitonyak,项目名称:ADPStampInventory,代码行数:70,代码来源:sqldialog.cpp

示例10: createXMLFileFromQuery

QString SafetVariable::createXMLFileFromQuery(const QSqlQuery& query, const QString& outputFileName ) const {
	
	QString result; 

	Q_ASSERT_X(!outputFileName.isEmpty(), 
			"SafetDocument::createXMLFileFromSQL()", 
			qPrintable(QObject::tr("outputFileName vacio")));
	
	if (outputFileName.isEmpty()){
		qDebug("cadena outputFileName vacia");
		return result;
    	}
	

	QFile file;
	bool open;
	QTextStream out;
	bool istext = outputFileName.compare("::text", Qt::CaseInsensitive) == 0;
	if ( !istext ) {	
		file.setFileName(outputFileName);
		open = file.open(QIODevice::WriteOnly | QIODevice::Text); 
	Q_ASSERT_X(open, 
			"SafetDocument::createXMLFileFromSQL()",
			qPrintable(QObject::tr("No se pudo crear el archivo XML correspondiente a la sentencia SQL.")));
		out.setDevice(&file);
	}
	else {
		out.setString(&result);		
	}
	
	
	
	QSqlRecord rec;
	rec = query.record();
	
	out << "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" << "\n";
	out << "<libsafetdb>" << "\n";
	
	QString cadena("");
	    	//qDebug("<: %s", qPrintable(x.setNum(j+1)), ">");
//		    qDebug("\t<Document>");
	   		
		out << "<Document>" << "\n" ;
	   	for (int i= 0; i< rec.count(); i++){
	   		//qDebug(qPrintable(rec.fieldName(i)));
	   		//qDebug(qPrintable(query.value(i).toString()));	
	   		cadena.append("<");
	   		cadena.append(rec.fieldName(i));
	   		cadena.append(">");
	   		cadena.append(query.value(i).toString());
	   		cadena.append("</");
	   		cadena.append(rec.fieldName(i));
	   		cadena.append(">");
	   		  	
//	   		qDebug(qPrintable(cadena));
	   		  	
	   		out << cadena << "\n" ;  	
	   		cadena.clear();
	   	}
//	    qDebug("</Document>");
	    
	out << "</Document>" << "\n" << "</libsafetdb>" << "\n";
	return result;
}
开发者ID:Cenditel,项目名称:pysafet,代码行数:64,代码来源:SafetVariable.cpp

示例11: receiptTablesData

QVariantMap ReceiptsPlugin::receiptTablesData(int card_id)
{
	qfLogFuncFrame() << card_id;
	QF_TIME_SCOPE("receiptTablesData()");
	QVariantMap ret;
	CardReader::CheckedCard checked_card = cardReaderPlugin()->checkCard(card_id);
	int current_stage_id = eventPlugin()->currentStageId();
	int run_id = checked_card.runId();
	int course_id = checked_card.courseId();
	int current_standings = 1;
	int competitors_finished = 0;
	QMap<int, int> best_laps; //< position->time
	///QMap<int, int> missing_codes; //< pos->code
	///QSet<int> out_of_order_codes;
	{
		qf::core::model::SqlTableModel model;
		qf::core::sql::QueryBuilder qb;
		qb.select2("competitors", "*")
				.select2("runs", "*")
				.select2("classes", "name")
				.select("COALESCE(competitors.lastName, '') || ' ' || COALESCE(competitors.firstName, '') AS competitorName")
				.from("runs")
				.join("runs.competitorId", "competitors.id")
				.join("competitors.classId", "classes.id")
				.where("runs.id=" QF_IARG(run_id));
		model.setQuery(qb.toString());
		model.reload();
		if(model.rowCount() == 1) {
			int class_id = model.value(0, "competitors.classId").toInt();
			{
				// find best laps for competitors class
				qf::core::sql::QueryBuilder qb_minlaps;
				// TODO: remove position field from DB in 0.1.5
				qb_minlaps.select("runlaps.position, MIN(runlaps.lapTimeMs) AS minLapTimeMs")
						.from("competitors")
						.joinRestricted("competitors.id", "runs.competitorId", "runs.stageId=" QF_IARG(current_stage_id) " AND competitors.classId=" QF_IARG(class_id), "JOIN")
						.joinRestricted("runs.id", "runlaps.runId", "runlaps.position > 0 AND runlaps.lapTimeMs > 0", "JOIN")
						.groupBy("runlaps.position");
				QString qs = qb_minlaps.toString();
				//qfInfo() << qs;
				qf::core::sql::Query q;
				q.exec(qs);
				while(q.next()) {
					int position = q.value("position").toInt();
					if(position == 0) {
						qfWarning() << "position == 0 in best runlaps";
						continue;
					}
					int lap = q.value("minLapTimeMs").toInt();
					if(lap == 0) {
						qfWarning() << "minLapTimeMs == 0 in best runlaps";
						continue;
					}
					best_laps[position] = lap;
					//qfInfo() << "bestlaps[" << pos << "] =" << lap;
				}
			}
			{
				// find current standings
				qf::core::sql::QueryBuilder qb;
				qb.select2("runs", "timeMs")
						.select("runs.disqualified OR runs.offRace OR runs.misPunch AS dis")
						.from("competitors")
						.joinRestricted("competitors.id", "runs.competitorId", "runs.stageId=" QF_IARG(current_stage_id) " AND competitors.classId=" QF_IARG(class_id))
						.where("runs.finishTimeMs > 0")
						.orderBy("misPunch, disqualified, offRace, runs.timeMs");
				//qfInfo() << qb.toString();
				qf::core::sql::Query q;
				q.exec(qb.toString(), qf::core::Exception::Throw);
				while (q.next()) {
					bool dis = q.value("dis").toBool();
					int time = q.value("timeMs").toInt();
					if(!dis) {
						if(time < checked_card.timeMs())
							current_standings++;
					}
					competitors_finished++;
				}
			}
		}
		qfu::TreeTable tt = model.toTreeTable();
		{
			qf::core::sql::QueryBuilder qb;
			qb.select2("courses", "length, climb")
					.select("(SELECT COUNT(*) FROM coursecodes WHERE courseId=courses.id) AS controlCount")
					.from("courses")
					.where("courses.id=" QF_IARG(course_id));
			qf::core::sql::Query q;
			q.exec(qb.toString());
			if(q.next()) {
				QSqlRecord rec = q.record();
				for (int i = 0; i < rec.count(); ++i) {
					QString fld_name = rec.fieldName(i);
					tt.setValue(fld_name, rec.value(i));
				}
			}
		}
		{
			qf::core::sql::QueryBuilder qb;
			qb.select2("config", "ckey, cvalue, ctype")
//.........这里部分代码省略.........
开发者ID:mezkov,项目名称:quickbox,代码行数:101,代码来源:receiptsplugin.cpp

示例12: varchar

SqlLiteTest::SqlLiteTest(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	
	QTextCodec::setCodecForLocale(QTextCodec::codecForLocale());
	QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//添加数据库
	db.setHostName("Erric");
	db.setDatabaseName("YSQ.db");
	db.setUserName("yinshangqqing");
	db.setPassword("123456");
	if(db.open())
	{
		qDebug()<<"Database opened success !";
		QSqlQuery query;
		bool success = query.exec("create table if not exists auto\
													(id int primary key,\
													 name varchar(20),\
													address varchar(30))");
		if(success)
		{
			qDebug()<<"table create success !";
		}
		else
		{
			qDebug()<<"table create fail !";
		}
		//查询
		query.exec("select * from auto");
		QSqlRecord rec = query.record();
		qDebug()<<"auto columns count: "<<rec.count();
		//插入记录
		QString insert_sql = "insert into auto values(1,'hao','beijing'),(2,'yun','shanghai'),(3,'qing','guangzhou')";
		QString select_sql = "select * from auto";
		success = query.prepare(insert_sql);
		if(success)
		{
			qDebug()<<"insert table success !";
		}
		else
		{
			qDebug()<<"insert table fail !";
			QSqlError lastError = query.lastError();
			qDebug()<<"lastError: "<<lastError;
		}
		success = query.prepare(select_sql);
		if(success)
		{
			//qDebug()<<"datas: "<<query.prepare(select_sql);
			qDebug()<<"select table success !";
			while(query.next())
			{
				int id = query.value(0).toInt();
				QString name = query.value(1).toString();
				QString address = query.value(2).toString();
				qDebug()<<QString("%1,%2,%3").arg(id).arg(name).arg(address);
			}
		}
		else
		{
			qDebug()<<"select table fail !";
			QSqlError lastError = query.lastError();
			qDebug()<<"lastError: "<<lastError;
		}
	}
开发者ID:yinshangqing,项目名称:sqlite,代码行数:65,代码来源:sqllitetest.cpp

示例13: sqlStatement

/*!
    Returns a SQL statement of type \a type for the table \a tableName
    with the values from \a rec. If \a preparedStatement is true, the
    string will contain placeholders instead of values.

    This method can be used to manipulate tables without having to worry
    about database-dependent SQL dialects. For non-prepared statements,
    the values will be properly escaped.
*/
QString QSqlDriver::sqlStatement(StatementType type, const QString &tableName,
                                 const QSqlRecord &rec, bool preparedStatement) const
{
    int i;
    QString s;
    s.reserve(128);
    switch (type) {
    case SelectStatement:
        for (i = 0; i < rec.count(); ++i) {
            if (rec.isGenerated(i))
                s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this)).append(QLatin1String(", "));
        }
        if (s.isEmpty())
            return s;
        s.chop(2);
        s.prepend(QLatin1String("SELECT ")).append(QLatin1String(" FROM ")).append(tableName);
        break;
    case WhereStatement:
        if (preparedStatement) {
            for (int i = 0; i < rec.count(); ++i) {
                s.append(prepareIdentifier(rec.fieldName(i), FieldName,this));
                if (rec.isNull(i))
                    s.append(QLatin1String(" IS NULL"));
                else
                    s.append(QLatin1String(" = ?"));
                s.append(QLatin1String(" AND "));
            }
        } else {
            for (i = 0; i < rec.count(); ++i) {
                s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this));
                QString val = formatValue(rec.field(i));
                if (val == QLatin1String("NULL"))
                    s.append(QLatin1String(" IS NULL"));
                else
                    s.append(QLatin1String(" = ")).append(val);
                s.append(QLatin1String(" AND "));
            }
        }
        if (!s.isEmpty()) {
            s.prepend(QLatin1String("WHERE "));
            s.chop(5); // remove tailing AND
        }
        break;
    case UpdateStatement:
        s.append(QLatin1String("UPDATE ")).append(tableName).append(
                 QLatin1String(" SET "));
        for (i = 0; i < rec.count(); ++i) {
            if (!rec.isGenerated(i))
                continue;
            s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this)).append(QLatin1Char('='));
            if (preparedStatement)
                s.append(QLatin1Char('?'));
            else
                s.append(formatValue(rec.field(i)));
            s.append(QLatin1String(", "));
        }
        if (s.endsWith(QLatin1String(", ")))
            s.chop(2);
        else
            s.clear();
        break;
    case DeleteStatement:
        s.append(QLatin1String("DELETE FROM ")).append(tableName);
        break;
    case InsertStatement: {
        s.append(QLatin1String("INSERT INTO ")).append(tableName).append(QLatin1String(" ("));
        QString vals;
        for (i = 0; i < rec.count(); ++i) {
            if (!rec.isGenerated(i))
                continue;
            s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this)).append(QLatin1String(", "));
            if (preparedStatement)
                vals.append(QLatin1Char('?'));
            else
                vals.append(formatValue(rec.field(i)));
            vals.append(QLatin1String(", "));
        }
        if (vals.isEmpty()) {
            s.clear();
        } else {
            vals.chop(2); // remove trailing comma
            s[s.length() - 2] = QLatin1Char(')');
            s.append(QLatin1String("VALUES (")).append(vals).append(QLatin1Char(')'));
        }
        break; }
    }
    return s;
}
开发者ID:3163504123,项目名称:phantomjs,代码行数:97,代码来源:qsqldriver.cpp

示例14: saveDocumentPositions

void DocumentSaverDB::saveDocumentPositions( KraftDoc *doc )
{
    DocPositionList posList = doc->positions();

    // invert all pos numbers to avoid a unique violation
    // FIXME: We need non-numeric ids
    QSqlQuery upq;
    QString queryStr = "UPDATE docposition SET ordNumber = -1 * ordNumber WHERE docID=";
    queryStr +=  doc->docID().toString();
    queryStr += " AND ordNumber > 0";
    upq.prepare( queryStr );
    upq.exec();

    int ordNumber = 1;

    QSqlTableModel model;
    model.setTable("docposition");
    model.setEditStrategy(QSqlTableModel::OnManualSubmit);

    QVector<int> deleteIds;

    DocPositionListIterator it( posList );
    while( it.hasNext() ) {
        DocPositionBase *dpb = it.next();

        DocPosition *dp = static_cast<DocPosition*>(dpb);
        QSqlRecord record ;
        bool doInsert = true;

        int posDbID = dp->dbId().toInt();
        kDebug() << "Saving Position DB-Id: " << posDbID << endl;

        if( dp->toDelete() ) {
            kDebug() << "Delete item " << dp->dbId().toString() << endl;

            // store the id to delete, rather than killing the model index.
            // did that before here, which removed wrong items.
            deleteIds << posDbID;

            // delete all existing attributes no, which will not disturb the model index
            dp->attributes().dbDeleteAll( dp->dbId() );
            continue;
        }

        if( posDbID > -1 ) {
            const QString selStr = QString("docID=%1 AND positionID=%2").arg( doc->docID().toInt() ).arg( posDbID );
            // kDebug() << "Selecting with " << selStr << endl;
            model.setFilter( selStr );
            model.select();
            if ( model.rowCount() > 0 ) {
                if( ! dp->toDelete() )
                    record = model.record(0);
                doInsert = false;
            } else {
                kError() << "ERR: Could not select document position record" << endl;
                return;
            }
        } else {
            // The record is new
            record = model.record();
        }

        if( record.count() > 0 ) {
            // kDebug() << "Updating position " << dp->position() << " is " << dp->text() << endl;
            QString typeStr = PosTypePosition;
            double price = dp->unitPrice().toDouble();

            if ( dp->type() == DocPositionBase::ExtraDiscount ) {
                typeStr = PosTypeExtraDiscount;
            }

            record.setValue( "docID",     QVariant(doc->docID().toInt()));
            record.setValue( "ordNumber", QVariant(ordNumber));
            record.setValue( "text",      QVariant(dp->text()));
            record.setValue( "postype",   QVariant(typeStr));
            record.setValue( "amount",    QVariant(dp->amount()));
            int unitId = dp->unit().id();
            record.setValue( "unit",      QVariant(unitId));
            record.setValue( "price",     QVariant(price));
            record.setValue( "taxType",   QVariant(dp->taxType()));

            ordNumber++; // FIXME

            if( doInsert ) {
                kDebug() << "Inserting!" << endl;
                model.insertRecord(-1, record);
                model.submitAll();
                dp->setDbId( KraftDB::self()->getLastInsertID().toInt() );
            } else {
                kDebug() << "Updating!" << endl;
                model.setRecord(0, record);
                model.submitAll();
            }
        } else {
            kDebug() << "ERR: No record object found!" << endl;
        }

        dp->attributes().save( dp->dbId() );

        QSqlError err = model.lastError();
//.........这里部分代码省略.........
开发者ID:KDE,项目名称:kraft,代码行数:101,代码来源:documentsaverdb.cpp

示例15: main

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QTextCodec::setCodecForLocale(QTextCodec::codecForLocale());
    QSqlDatabase db =QSqlDatabase::addDatabase("QSQLITE");
    db.setHostName("easybook-3313b0");          //设置数据库主机名
    db.setDatabaseName("qtDB.db");              //设置数据库名
    db.setUserName("zhouhejun");                //设置数据库用户名
    db.setPassword("123456");                   //设置数据库密码
    db.open();                             		//打开连接

    //创建数据库表
    QSqlQuery query;
    bool success=query.exec("create table automobil(id int primary key,attribute varchar,type varchar,kind varchar,nation int,carnumber int,elevaltor int,distance int,oil int,temperature int)");
    if(success)
        qDebug()<<QObject::tr("数据库表创建成功!\n");
    else
        qDebug()<<QObject::tr("数据库表创建失败!\n");

    //查询
    query.exec("select * from automobil");
    QSqlRecord rec = query.record();
    qDebug() << QObject::tr("automobil表字段数:" )<< rec.count();

    //插入记录
    QTime t;
    t.start();
    query.prepare("insert into automobil values(?,?,?,?,?,?,?,?,?,?)");

    long records=100;
    for(int i=0;i<records;i++)
    {
        query.bindValue(0,i);
        query.bindValue(1,"四轮");
        query.bindValue(2,"轿车");
        query.bindValue(3,"富康");
        query.bindValue(4,rand()%100);
        query.bindValue(5,rand()%10000);
        query.bindValue(6,rand()%300);
        query.bindValue(7,rand()%200000);
        query.bindValue(8,rand()%52);
        query.bindValue(9,rand()%100);

        success=query.exec();
        if(!success)
        {
            QSqlError lastError=query.lastError();
            qDebug()<<lastError.driverText()<<QString(QObject::tr("插入失败"));
        }
    }
    qDebug()<<QObject::tr("插入 %1 条记录,耗时:%2 ms").arg(records).arg(t.elapsed());

    //排序
    t.restart();
    success=query.exec("select * from automobil order by id desc");
    if(success)
        qDebug()<<QObject::tr("排序 %1 条记录,耗时:%2 ms").arg(records).arg(t.elapsed());
    else
        qDebug()<<QObject::tr("排序失败!");

    //更新记录
    t.restart();
    for(int i=0;i<records;i++)
    {
       query.clear();
       query.prepare(QString("update automobil set attribute=?,type=?,"
                             "kind=?,nation=?,"
                             "carnumber=?,elevaltor=?,"
                             "distance=?,oil=?,"
                             "temperature=? where id=%1").arg(i));

       query.bindValue(0,"四轮");
       query.bindValue(1,"轿车");
       query.bindValue(2,"富康");
       query.bindValue(3,rand()%100);
       query.bindValue(4,rand()%10000);
       query.bindValue(5,rand()%300);
       query.bindValue(6,rand()%200000);
       query.bindValue(7,rand()%52);
       query.bindValue(8,rand()%100);

       success=query.exec();
       if(!success)
       {
           QSqlError lastError=query.lastError();
           qDebug()<<lastError.driverText()<<QString(QObject::tr("更新失败"));
       }
    }
    qDebug()<<QObject::tr("更新 %1 条记录,耗时:%2 ms").arg(records).arg(t.elapsed());

    //删除
    t.restart();
    query.exec("delete from automobil where id=15");
    qDebug()<<QObject::tr("删除一条记录,耗时:%1 ms").arg(t.elapsed());

    return 0;
    //return a.exec();
}
开发者ID:Pengfei-Gao,项目名称:develop-reference-data,代码行数:98,代码来源:main.cpp


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