Пример #1
0
/*!
    \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;
}
Пример #2
0
// 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();
    }
  }
}
Пример #3
0
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;
}
Пример #4
0
bool SqlDbBackend::save( const OidType& oid, const RelationInfo* relationInfo, const OidType& relatedOid )
{
	QString searchTable;
	OidType searchOid;
	OidType setOid;
	bool update;
	QSqlRecord *record;

	if ( relationInfo->isOneToOne() ) {
		QString related = relationInfo->relatedClassInfo()->name();
		QString parent = relationInfo->parentClassInfo()->name();
		if ( related >= parent ) {
			searchTable = parent;
			searchOid = oid;
			setOid = relatedOid;
		} else {
			searchTable = related;
			searchOid = relatedOid;
			setOid = oid;
		}
	} else {
		searchTable = relationInfo->parentClassInfo()->name();
		searchOid = oid;
		setOid = relatedOid;
	}

	// We shouldn't store anything of any object with oid zero
	if ( searchOid == 0 )
		return true;

	kdDebug() << "Search table: " << searchTable << endl;
	QSqlCursor cursor( searchTable );
	//TODO: Probably the object should always already exist as commitObjects() is
	// called before commitRelations(). So maybe if record isn't found should be
	// considered an error.
	if ( oid == 0 ) {
		// Creates a unique oid. TODO: Should it ever happen?
		cursor.select();
		record = cursor.primeInsert();
		update = false;
	} else {
		cursor.select( "to_number( " + oidFieldName() + ", '9999999999G0') = " + oidToString( searchOid ) );
		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(), searchOid );
	record->setGenerated( oidFieldName(), true );
	record->setValue( sequenceFieldName(), newSeq() );
	record->setGenerated( sequenceFieldName(), true );

	if ( setOid != 0 )
		record->setValue( relationInfo->name(), setOid );
	else
		record->setNull( relationInfo->name() );
	record->setGenerated( relationInfo->name(), true );

	if ( update ) {
		if (! cursor.update() ) {
			kdDebug() << k_funcinfo << " -> " << cursor.lastError().text() << endl;
			kdDebug() << k_funcinfo << " -> " << cursor.executedQuery() << endl;
			//delete cursor;
			ERROR( "Update failed" );
		}
	} else {
		if ( ! cursor.insert() ) {
			kdDebug() << k_funcinfo << " -> " << cursor.lastError().text() << endl;
			kdDebug() << k_funcinfo << " -> " << cursor.executedQuery() << endl;
			//delete cursor;
			ERROR( "Insert failed" );
		}
	}
	//delete cursor;
	return true;
}
Пример #5
0
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;
}
Пример #6
0
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),
						  return false);
				if(serial_ix >= 0 && !serial_ix_explicitly_set) {
					QVariant v = q.lastInsertId();
					qfDebug() << "\tsetting serial index:" << serial_ix << "to generated value:" << v;
					if(v.isValid()) {
						row_ref.setValue(serial_ix, v);
						row_ref.setDirty(serial_ix, false);
					}
					else {
						qfWarning() << "Serial field will not be initialized properly. This can make current transaction aborted.";
					}
				}
				if(primary_ix >= 0) {
					/// update foreign keys in the slave tables
					qf::core::utils::Table::Field pri_ix_fld = row_ref.fields().value(primary_ix);
					QString master_key = pri_ix_fld.name();
					qfDebug() << "\t master_key:" << master_key;
					QString slave_key = m_foreignKeyDependencies.value(master_key);
					if(!slave_key.isEmpty()) {
						qfDebug() << "\tsetting value of foreign key" << slave_key << "to value of master key:" << row_ref.value(master_key).toString();
						row_ref.setValue(slave_key, row_ref.value(master_key));
					}
				}
			}
			else {
				QString errs = tr("Error executing query: %1\n %2").arg(qs).arg(q.lastError().text());
				if(throw_exc)
					QF_EXCEPTION(errs);
				else
					qfError() << errs;
			}
		}
Пример #7
0
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(")");
        }
        desc.Null = !info.requiredStatus();
        ColumnDescriptions.append(desc);
    }
    return ColumnDescriptions;
}
Пример #8
0
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();
  }   
}
Пример #9
0
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;

}
Пример #10
0
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!
  }
}
Пример #11
0
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;
}
Пример #12
0
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")
					.from("config")
					.where("ckey LIKE 'event.%'");
			qf::core::sql::Query q;
			q.exec(qb.toString());
			while(q.next()) {
				QVariant v = qf::core::Utils::retypeStringValue(q.value("cvalue").toString(), q.value("ctype").toString());
				tt.setValue(q.value("ckey").toString(), v);
			}
		}
		tt.setValue("stageCount", eventPlugin()->stageCount());
		tt.setValue("currentStageId", eventPlugin()->currentStageId());
		qfDebug() << "competitor:\n" << tt.toString();
		ret["competitor"] = tt.toVariant();
	}
	{
		qfu::TreeTable tt;
		tt.appendColumn("position", QVariant::Int);
		tt.appendColumn("code", QVariant::Int);
		tt.appendColumn("stpTimeMs", QVariant::Int);
		tt.appendColumn("lapTimeMs", QVariant::Int);
		tt.appendColumn("lossMs", QVariant::Int);
 		QMapIterator<QString, QVariant> it(checked_card);
		while(it.hasNext()) {
			it.next();
			if(it.key() != QLatin1String("punches"))
				tt.setValue(it.key(), it.value());
		}
		tt.setValue("isOk", checked_card.isOk());
		int position = 0;
		for(auto v : checked_card.punches()) {
			CardReader::CheckedPunch punch(v.toMap());
			qfu::TreeTableRow ttr = tt.appendRow();
			++position;
			int code = punch.code();
			ttr.setValue("position", position);
			ttr.setValue("code", code);
			ttr.setValue("stpTimeMs", punch.stpTimeMs());
			int lap = punch.lapTimeMs();
			ttr.setValue("lapTimeMs", lap);
			int best_lap = best_laps.value(position);
			if(lap > 0 && best_lap > 0) {
				int loss = lap - best_lap;
				ttr.setValue("lossMs", loss);
			}
		}
		/*
		{
			// runlaps table contains also finish time entry, it is under FINISH_PUNCH_POS
			// currently best_laps[999] contains best finish lap time for this class
			int loss = 0;
			int best_lap = best_laps.value(CardReader::CardReaderPlugin::FINISH_PUNCH_POS);
			if(best_lap > 0)
				loss = checked_card.finishLapTimeMs() - best_lap;
			//qfInfo() << "control_count:" << control_count << "finishLapTimeMs:" << checked_card.finishLapTimeMs() << "- best_lap:" << best_lap << "=" << loss;
			tt.setValue("finishLossMs", loss);
		}
		{
			QVariantList mc;
			for(auto i : missing_codes.keys())
				mc.insert(mc.count(), QVariantList() << i << missing_codes.value(i));
			//mc.insert(mc.count(), QVariantList() << 1 << 101);
			tt.setValue("missingCodes", mc);
		}
		*/
		tt.setValue("currentStandings", current_standings);
		tt.setValue("competitorsFinished", competitors_finished);
		tt.setValue("timeMs", checked_card.timeMs());

		qfDebug() << "card:\n" << tt.toString();
		ret["card"] = tt.toVariant();
	}
	return ret;
}
Пример #13
0
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;
		}
	}
Пример #14
0
/*!
    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;
}
Пример #15
0
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();
        if( err.type() != QSqlError::NoError ) {
            kDebug() << "SQL-ERR: " << err.text() << " in " << model.tableName() << endl;
        }

    }
    model.submitAll();

    /*  remove the docpositions that were marked to be deleted */
    if( deleteIds.count() ) {
        QSqlQuery delQuery;
        delQuery.prepare( "DELETE FROM docposition WHERE positionID=:id" );
        foreach( int id, deleteIds ) {
            kDebug() << "Deleting attribute id " << id;
            delQuery.bindValue( ":id", id );
            delQuery.exec();
        }
Пример #16
0
// this is a very basic test for drivers that cannot create/delete tables
// it can be used while developing new drivers,
// it's original purpose is to test ODBC Text datasources that are basically
// to stupid to do anything more advanced than SELECT/INSERT/UPDATE/DELETE
// the datasource has to have a table called "qtest_basictest" consisting
// of a field "id"(integer) and "name"(char/varchar).
void tst_QSql::basicDriverTest()
{
    int argc = 0;
    QApplication app( argc, 0, false );
    tst_Databases dbs;
    dbs.open();

    foreach( const QString& dbName, dbs.dbNames )
    {
        QSqlDatabase db = QSqlDatabase::database( dbName );
        QVERIFY_SQL( db, isValid() );

        QStringList tables = db.tables();
        QString tableName;

        if ( tables.contains( "qtest_basictest.txt" ) )
            tableName = "qtest_basictest.txt";
        else if ( tables.contains( "qtest_basictest" ) )
            tableName = "qtest_basictest";
        else if ( tables.contains( "QTEST_BASICTEST" ) )
            tableName = "QTEST_BASICTEST";
        else {
            QVERIFY( 1 );
            continue;
        }

        qDebug( qPrintable( QLatin1String( "Testing: " ) + tst_Databases::dbToString( db ) ) );

        QSqlRecord rInf = db.record( tableName );
        QCOMPARE( rInf.count(), 2 );
        QCOMPARE( rInf.fieldName( 0 ).toLower(), QString( "id" ) );
        QCOMPARE( rInf.fieldName( 1 ).toLower(), QString( "name" ) );

#ifdef QT3_SUPPORT
        QSqlRecord* rec = 0;
        Q3SqlCursor cur( tableName, true, db );
        QVERIFY_SQL( cur, select() );
        QCOMPARE( cur.count(), 2 );
        QCOMPARE( cur.fieldName( 0 ).lower(), QString( "id" ) );
        QCOMPARE( cur.fieldName( 1 ).lower(), QString( "name" ) );

        rec = cur.primeDelete();
        rec->setGenerated( 0, false );
        rec->setGenerated( 1, false );
        QVERIFY_SQL( cur, del() );
        QVERIFY_SQL( cur, select() );
        QCOMPARE( cur.at(), int( QSql::BeforeFirst ) );
        QVERIFY( !cur.next() );
        rec = cur.primeInsert();
        rec->setValue( 0, 1 );
        rec->setValue( 1, QString( "Harry" ) );
        QVERIFY_SQL( cur, insert( false ) );
        rec = cur.primeInsert();
        rec->setValue( 0, 2 );
        rec->setValue( 1, QString( "Trond" ) );
        QVERIFY_SQL( cur, insert( true ) );
        QVERIFY_SQL( cur, select( cur.index( QString( "id" ) ) ) );
        QVERIFY_SQL( cur, next() );
        QCOMPARE( cur.value( 0 ).toInt(), 1 );
        QCOMPARE( cur.value( 1 ).toString().stripWhiteSpace(), QString( "Harry" ) );
        QVERIFY_SQL( cur, next() );
        QCOMPARE( cur.value( 0 ).toInt(), 2 );
        QCOMPARE( cur.value( 1 ).toString().stripWhiteSpace(), QString( "Trond" ) );
        QVERIFY( !cur.next() );
        QVERIFY_SQL( cur, first() );
        rec = cur.primeUpdate();
        rec->setValue( 1, QString( "Vohi" ) );
        QVERIFY_SQL( cur, update( true ) );
        QVERIFY_SQL( cur, select( "id = 1" ) );
        QVERIFY_SQL( cur, next() );
        QCOMPARE( cur.value( 0 ).toInt(), 1 );
        QCOMPARE( cur.value( 1 ).toString().stripWhiteSpace(), QString( "Vohi" ) );
#endif
    }

    dbs.close();
    QVERIFY( 1 ); // make sure the test doesn't fail if no database drivers are there
}
Пример #17
0
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();
}