Example #1
0
bool TableModel::setData(const QModelIndex &index, const QVariant &value, int /* role */)
{
    //Make sure tables without primary key don't propagate changes.
    if(primary_key.isEmpty())
        return false;

    //Get the row data into a QSqlRecord object
    QSqlRecord rec = record(index.row());

    //Get parameters for UPDATE query
    edit_column = QString("\"" + rec.fieldName(index.column()) + "\"");
    edit_index = index;
    edit_value = value;

    //Check for primary keys to pass to UPDATE statment
    for(int column = 0; column < rec.count(); column++) {
        if(primary_key.contains(QString("\"" + rec.fieldName(column)) + "\""))
                primary_key_values.append(rec.value(column).toString());
    }

    //If UPDATE statement fails, do not store in cache
    //Clear the primary key values either case
    if(update()) {
        cache_values.insert(index, value);
        primary_key_values.clear();
        emit dataChanged(index, index);
        return true;
    }
    else {
        primary_key_values.clear();
        return false;
    }
}
Example #2
0
bool SqlFileExporter::exportTableAsCSV(QSqlQuery query, const QString &outputpath, bool csv) {
    QFile outputfile(outputpath);
    if (!outputfile.open(QIODevice::WriteOnly))
        return false;

    QString delimiter = "\t";
    if (csv)
        delimiter = ",";

    QSqlRecord record = query.record();
    for (int i = 0; i < record.count(); ++i) {
        if (i != 0)
            outputfile.write(delimiter.toUtf8());
        if (csv)
            outputfile.write(quoteCSVColumn(record.fieldName(i)).toUtf8());
        else
            outputfile.write(record.fieldName(i).toUtf8());
    }
    outputfile.write("\n");

    do {
        record = query.record();
        for (int i = 0; i < record.count(); ++i) {
            if (i != 0)
                outputfile.write(delimiter.toUtf8());
            if (csv)
                outputfile.write(quoteCSVColumn(record.value(i).toString()).toUtf8());
            else
                outputfile.write(record.value(i).toString().toUtf8());
        }
        outputfile.write("\n");
    } while(query.next());
    outputfile.close();
    return true;
}
Example #3
0
void tst_QSqlDriver::record()
{
    QFETCH_GLOBAL(QString, dbName);
    QSqlDatabase db = QSqlDatabase::database(dbName);
    CHECK_DATABASE(db);

    QString tablename(qTableName("relTEST1", __FILE__));
    QStringList fields;
    fields << "id" << "name" << "title_key" << "another_title_key";

    //check we can get records using an unquoted mixed case table name
    QSqlRecord rec = db.driver()->record(tablename);
    QCOMPARE(rec.count(), 4);

    if (db.driverName().startsWith("QIBASE")|| db.driverName().startsWith("QOCI") || db.driverName().startsWith("QDB2"))
        for(int i = 0; i < fields.count(); ++i)
            fields[i] = fields[i].toUpper();

    for (int i = 0; i < fields.count(); ++i)
        QCOMPARE(rec.fieldName(i), fields[i]);

    if (db.driverName().startsWith("QIBASE") || db.driverName().startsWith("QOCI") || db.driverName().startsWith("QDB2"))
        tablename = tablename.toUpper();
    else if (db.driverName().startsWith("QPSQL"))
        tablename = tablename.toLower();

    if(!db.driverName().startsWith("QODBC") && !db.databaseName().contains("PostgreSql")) {
        //check we can get records using a properly quoted table name
        rec = db.driver()->record(db.driver()->escapeIdentifier(tablename,QSqlDriver::TableName));
        QCOMPARE(rec.count(), 4);
    }

    for (int i = 0; i < fields.count(); ++i)
        QCOMPARE(rec.fieldName(i), fields[i]);

    if( db.driverName().startsWith("QIBASE") || db.driverName().startsWith("QOCI") || db.driverName().startsWith("QDB2"))
        tablename = tablename.toLower();
    else if (db.driverName().startsWith("QPSQL"))
        tablename = tablename.toUpper();

    //check that we can't get records using incorrect tablename casing that's been quoted
    rec = db.driver()->record(db.driver()->escapeIdentifier(tablename,QSqlDriver::TableName));
    if (tst_Databases::isMySQL(db)
      || db.driverName().startsWith("QSQLITE")
      || db.driverName().startsWith("QTDS")
      || tst_Databases::isSqlServer(db)
      || tst_Databases::isMSAccess(db))
        QCOMPARE(rec.count(), 4); //mysql, sqlite and tds will match
    else
        QCOMPARE(rec.count(), 0);

}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  update account list
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void MainWindow::updateAccountList()
{
    qDebug() << "Entering updateAccountList";
    ui->accountList->clear();
    ui->accountEdit->clear();
    ui->passEdit->clear();
    QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
    db.setDatabaseName( "users.db3" );
    if( !db.open() )
    {
      qDebug() << db.lastError();
      qFatal( "Failed to connect." );
    }

    QSqlQuery qry;
    QString queryString = "SELECT * FROM '" + QString::fromStdString(encryption::encrypt(username, 29, 41)) + "'";\
    qDebug() << queryString;
    qry.prepare(queryString);
    if( !qry.exec() )
      qDebug() << qry.lastError();
    else
    {
        qDebug( "entries Selected!" );

        QSqlRecord rec = qry.record();

        int cols = rec.count();

        for( int c=0; c<cols; c++ )
            qDebug() << QString( "Column %1: %2" ).arg( c ).arg( rec.fieldName(c) );

        for( int r=0; qry.next(); r++ )
        {
            ui->accountList->addItem(QString::fromStdString(encryption::decrypt(qry.value(0).toString().toStdString(), 29, 41)));
            for( int c=0; c<cols; c++ )
            {
                qDebug() << QString( "Row %1, %2: %3" ).arg( r ).arg( rec.fieldName(c) ).arg( qry.value(c).toString() );
            }//for
        }//for
    }

    if (ui->accountList->count() == 0)
    {
        std::string message = "It seems you don't have any entries associated with your account\n"
                                "Please enter a new username/password combo in the lineEdit boxes in the bottom right\n"
                                "You can then select \"Add\" or \"Save\" to add the combo to your account\n\n"
                                "Once you have a couple entries you can select said entries from the listWidget on the middle left\n"
                                "Clicking on entries will populate the lineEdits and you may edit thier information";
    }
    db.close();
    ui->accountList->sortItems(Qt::AscendingOrder);
}
Example #5
0
void IndexDialog::tableChanged(const QString &tb)
{
    tbname = tb;
    tbColumnList->clearContents();

    QSqlDatabase db = QSqlDatabase::database(conname);
    QSqlRecord record = db.record(tbname);
    int count = record.count();
    tbColumnList->setRowCount(count);

    for(int i=0;i<count;i++){
        QTableWidgetItem *item = new QTableWidgetItem;
        item->setData(Qt::EditRole,false);
        item->setFlags(Qt::ItemIsEnabled);
        tbColumnList->setItem(i,0,item);

        item = new QTableWidgetItem;
        item->setText(record.fieldName(i));
        tbColumnList->setItem(i,1,item);

        item = new QTableWidgetItem;
        item->setText(QString());
        tbColumnList->setItem(i,2,item);

        item = new QTableWidgetItem;
        item->setText(QString());
        tbColumnList->setItem(i,3,item);
    }
}
Example #6
0
QDateTime Database::replaceCacheRecordByServerRecord(const QSqlDatabase& dbCache, const QString& table, const QSqlQuery& queryMaster)
{
    QDateTime updated;    
    QSqlRecord record = queryMaster.record();
    int fieldUpdated = record.indexOf("updated");
    if (fieldUpdated == -1)
    {
        fieldUpdated = record.indexOf("created");
    }

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

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

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

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

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

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

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

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

    return updated;
}
bool SqlQueryUtils::getQueryData(QSqlDatabase &connection, const QString &query, int offset, int limit,
        const QVariantMap &bindValues, const QString &keyColumn, const QString &revisionColumn,
        QList<DataItem> *results, QSqlError *error) {
    QElapsedTimer timer;
    timer.start();
    results->clear();

    QSqlQuery sqlQuery(connection);
    QString fullQuery = extendQuery(query, offset, limit);
    SqlQueryUtils::prepareQuery(fullQuery, bindValues, &sqlQuery);

    bool success = sqlQuery.exec();
    if (!success) {
        *error = sqlQuery.lastError();
        qDebug() << "query error: " << *error;
        return false;
    }
    QList<QString> field;
    // Build the result structure.
    while (sqlQuery.next()) {
        QVariantMap recordMap;
        if (field.isEmpty()) {
            QSqlRecord record = sqlQuery.record();
            for (int i = 0, n = record.count(); i < n; i++) {
                field.append(record.fieldName(i));
            }
        }
        for (int i = 0, n = field.size(); i < n; i++) {
            QVariant value = sqlQuery.value(i);
            // JavaScript/QML doesn't support 64bit integers (everything is converted to double)
            // so convert to string here to make sure we don't run into trouble.
            // In the long term it will be cleaner to move this code into something like a
            // query decorator instead of the core query code.
            if (value.type() == QVariant::LongLong || value.type() == QVariant::ULongLong) {
                value = value.toString();
            }
            recordMap.insert(field.at(i), value);
        }

        // the data item key
        QString keyId;
        if (!keyColumn.isEmpty() && recordMap.contains(keyColumn)) {
            keyId = recordMap.value(keyColumn).toString();
        }

        // the data item revision
        quint64 revision = 0;
        bool revisionOK = false;
        if (!revisionColumn.isEmpty() && recordMap.contains(revisionColumn)) {
            revision = recordMap.value(revisionColumn).toULongLong(&revisionOK);
        }
        DataRevision dataRev = revisionOK ? DataRevision(new NumericRevision(revision)) : DataRevision();

        results->append(DataItem(keyId, dataRev, recordMap));
    }

    qDebug() << "Query executed: " << sqlQuery.executedQuery();
    qDebug() << "Loaded " << results->size() << " items in " << timer.elapsed() << "ms";
    return true;
}
bool SqlQueryUtils::getSingleQueryValue(QSqlDatabase &connection, const QString &query, const QVariantMap &bindValues,
        const QString &resultName, QVariant *resultValue, QSqlError *error) {
    QElapsedTimer timer;
    timer.start();

    QSqlQuery sqlQuery(connection);
    SqlQueryUtils::prepareQuery(query, bindValues, &sqlQuery);

    *resultValue = QVariant();
    bool success = sqlQuery.exec();
    if (success && sqlQuery.next()) {
        QSqlRecord record = sqlQuery.record();
        int recCount = record.count();
        for (int i = 0; i < recCount; ++i) {
            // Verify result column name if its provided by the caller
            // Otherwise grab the first value and return it
            if (resultName.isEmpty() || resultName.compare(record.fieldName(i), Qt::CaseInsensitive) == 0) {
                *resultValue = sqlQuery.value(i);
                break;
            }
        }
    } else {
        *error = sqlQuery.lastError();
        qDebug() << "query error: " << *error;
        return false;
    }

    qDebug() << "Fetched single value=" << *resultValue << " in " << timer.elapsed() << "ms";
    return true;
}
Example #9
0
ResultSet  DBService::query(const QString& sqlQuery)
{
//    qDebug()<<"query sql : "<<sqlQuery;
    ResultSet results;
    isValid = true;
    if(!open())
    {
        isValid = false;
        return results;
    }
    QSqlQuery sql_query(database);
    sql_query.prepare(sqlQuery);
    if(!sql_query.exec())
    {
        isValid = false;
        qDebug()<<sql_query.lastError();
        return results;
    }
    else
    {
        QSqlRecord record = sql_query.record();
        while(sql_query.next())
        {
            ResultRow resMap;
            for(int i = 0;i < record.count();i++)
            {
                resMap.insert(record.fieldName(i),sql_query.value(i).toString());
            }
            results.resultList.append(resMap);
        }

    }
    close();
    return results;
}
Example #10
0
void QxtSqlPackage::insert(QSqlQuery query)
{
    map.clear();
    record = -1;

    /*query will be invalid if next is not called first*/
    if (!query.isValid())
        query.next();

    QSqlRecord infoRecord = query.record();
    int iNumCols = infoRecord.count();
    QVector<QString> tableMap = QVector<QString>(iNumCols);

    /*first create a map of index->colname pairs*/
    for (int iLoop = 0; iLoop < iNumCols; iLoop++)
    {
        tableMap[iLoop] = infoRecord.fieldName(iLoop);
    }

    /*now use this created map to get column names
     *this should be faster than querying the QSqlRecord every time
     *but that depends on the databasetype and size of the table (number of rows and cols)
     */
    do
    {
        QHash<QString, QString> hash;
        for (int iColLoop = 0; iColLoop < iNumCols; iColLoop++)
        {
            hash[tableMap[iColLoop]] = query.value(iColLoop).toString();
        }
        map.append(hash);

    }
    while (query.next());
}
Example #11
0
QList<QVariantMap> FetchSqlite::query(const QString &sql, QMap<QString, QVariant> bindObjects)
{
    //qDebug() << "query: " << sql;
    QSqlQuery query(m_db);
    query.prepare(sql);
    foreach(const QString &variableName, bindObjects.keys()) {
        query.bindValue(variableName, bindObjects.value(variableName));
        //qDebug() << "* Bound " << variableName << " to " << query.boundValue(variableName);
    }

    if(!query.exec()) {
        QSqlError error = m_db.lastError();
        //qDebug() << "query failed: " << error.text() << " (" << error.type() << ", " << error.number() << ")";
        //qDebug() << query.lastQuery();
    }

    QList<QVariantMap> result;
    while(query.next()) {
        QVariantMap recordValues;
        QSqlRecord record = query.record();
        for(int field=0; field<record.count(); field++) {
            QVariant value = record.value(field);
            recordValues.insert(record.fieldName(field), value  );
        }
        result << recordValues;
    }
    return result;
}
Example #12
0
/*! \internal
    Set a record for OnFieldChange and OnRowChange.
*/
bool QSqlTableModelPrivate::setRecord(int row, const QSqlRecord &record)
{
    Q_Q(QSqlTableModel);
    bool isOk = true;

    QSqlTableModel::EditStrategy oldStrategy = strategy;

    // FieldChange strategy makes no sense when setting an entire row
    if (strategy == QSqlTableModel::OnFieldChange)
        strategy = QSqlTableModel::OnRowChange;
    for (int i = 0; i < record.count(); ++i) {
        int idx = nameToIndex(record.fieldName(i));
        if (idx == -1)
            continue;
        QModelIndex cIndex = q->createIndex(row, idx);
        QVariant value = record.value(i);
        QVariant oldValue = q->data(cIndex);
        if (oldValue.isNull() || oldValue != value)
            isOk &= q->setData(cIndex, value, Qt::EditRole);
    }
    if (isOk && oldStrategy == QSqlTableModel::OnFieldChange)
        q->submitAll();
    strategy = oldStrategy;

    return isOk;
}
QList<T *> DataMapper<Subclass, T, I>::basicFind(const QString & sql)
{
    QList<T *> results;

    QSqlQuery query = getDatabase().build(sql);

    if (query.exec())
    {
        QSqlRecord record = query.record();
        QMap<QString, int> indices;

        for (unsigned i = 0;i < record.count();++i)
        {
            indices[record.fieldName(i)] = i;
        }

        while (query.next())
        {
            QVariantMap map;

            for (QString fieldName : indices.keys())
            {
                map[fieldName] = query.value(indices[fieldName]);
            }

            results << obtainFromIdentityMap(map);
        }
    }

    return results;
}
Example #14
0
/*!
    \fn MPeluqueria::agregarServicio( QVariant desc, QVariant precio, QVariant fecha, QVariant id_mascota )
 */
bool MPeluqueria::agregarServicio( QVariant desc, QVariant precio, QVariant fecha, QVariant id_mascota )
{
/* if( !mascota.isValid() )
 {
   qDebug( "Inidce Mascota es invalido" );
   return false;
 }
 QVariant id_mascota = relationModel( 1 )->data( mascota, 0 );
 if( id_mascota.isValid() && id_mascota.toInt() <= 0 )
 {return false;}*/
 QSqlRecord registro = record();
 registro.setValue( 1, id_mascota );
 registro.setValue( 2, desc );
 registro.setValue( 3, precio );
 registro.setValue( 4, fecha );
 for( int i = 0; i<registro.count(); i++ )
 {
   qDebug( QString( "Campo: %1, generado? %2, null? %3, valor? |%4|" ).arg( registro.fieldName( i ) ).arg( registro.isGenerated( i ) ).arg( registro.isNull( i ) ).arg( registro.value( i ).toString() ).toLocal8Bit() );
 }
 if( insertRecord( -1, registro ) )
 {
   qDebug( "Registro de servicio agregado correctamente" );
   return true;
 }
 else
 {
   qDebug( "Error al insertar registro de servicio de mascota" );
   qDebug( QString( "Detalles: tipo: %1, errno: %2, descripcion: %3" ).arg( lastError().type() ).arg( lastError().number() ).arg( lastError().text() ).toLocal8Bit() );
   return false;
 }
}
QString QSqlRecordProto::fieldName(int index) const
{
  QSqlRecord *item = qscriptvalue_cast<QSqlRecord*>(thisObject());
  if (item)
    return item->fieldName(index);
  return QString();
}
Example #16
0
void SQLite::slotResults(const QList<QSqlRecord> &result)
{
    qDebug() << __PRETTY_FUNCTION__;
    qDebug() << "count="<<result.count();


    QVariantList val;

    QListIterator<QSqlRecord> sqlRecordsIterator(result);

    while(sqlRecordsIterator.hasNext())
    {
        QSqlRecord sqlRecord = sqlRecordsIterator.next();
        QVariantMap dataMap;
        for(int column = 0; column < sqlRecord.count(); column++)
        {
            //qDebug() << sqlRecord.fieldName(column);
            dataMap.insert(sqlRecord.fieldName(column), sqlRecord.value(column));
        }
        val.append(QVariant::fromValue(dataMap));
    }
    qDebug() << "count of list=" << val.count();
    resultsReady(val, m_query);
    setStatus(Ready);
}
Example #17
0
QList<QVariantList> TcDataAccess::fetchAllList(const QString &sql,
            const QVariantList &bind /* = QVariantList() */)
{
    _prepareExec(sql, bind);

    QList<QVariantList> result;
    QVariantList row;
    QSqlRecord rec;
    while (_query->next())
    {
        rec = _query->record();
        if (result.isEmpty())
        {
            for (int i = 0; i < rec.count(); i++)
            {
                row << _case(rec.fieldName(i));
            }
            result << row;
            row.clear();
        }
        for (int i = 0; i < rec.count(); i++)
        {
            row << _trim(rec.value(i));
        }
        result << row;
        row.clear();
    }
    return result;
}
Example #18
0
bool MSqlQuery::seekDebug(const char *type, bool result,
                          int where, bool relative) const
{
    if (result && VERBOSE_LEVEL_CHECK(VB_DATABASE, LOG_DEBUG))
    {
        QString str;
        QSqlRecord rec = record();

        for (long int i = 0; i < rec.count(); i++)
        {
            if (!str.isEmpty())
                str.append(", ");

            str.append(rec.fieldName(i) + " = " +
                       value(i).toString());
        }

        if (QString("seek")==type)
        {
            LOG(VB_DATABASE, LOG_DEBUG,
                QString("MSqlQuery::seek(%1,%2,%3) Result: \"%4\"")
                .arg(m_db->MSqlDatabase::GetConnectionName())
                .arg(where).arg(relative)
                .arg(str));
        }
        else
        {
            LOG(VB_DATABASE, LOG_DEBUG,
                QString("MSqlQuery::%1(%2) Result: \"%3\"")
                .arg(type).arg(m_db->MSqlDatabase::GetConnectionName())
                .arg(str));
        }
    }
    return result;
}
Example #19
0
/*!
    Sets the values at the specified \a row to the values of \a
    record. Returns true if all the values could be set; otherwise
    returns false.

    \sa record()
*/
bool QSqlTableModel::setRecord(int row, const QSqlRecord &record)
{
    Q_D(QSqlTableModel);
    Q_ASSERT_X(row >= 0, "QSqlTableModel::setRecord()", "Cannot set a record to a row less than 0");
    if (row >= rowCount())
        return false;

    bool isOk = true;
    switch (d->strategy) {
    case OnFieldChange:
    case OnRowChange:
        return d->setRecord(row, record);
    case OnManualSubmit: {
        QSqlTableModelPrivate::ModifiedRow &mrow = d->cache[row];
        if (mrow.op == QSqlTableModelPrivate::None) {
            mrow.op = QSqlTableModelPrivate::Update;
            mrow.rec = d->rec;
            mrow.primaryValues = d->primaryValues(indexInQuery(createIndex(row, 0)).row());
        }
        for (int i = 0; i < record.count(); ++i) {
            int idx = mrow.rec.indexOf(record.fieldName(i));
            if (idx == -1)
                isOk = false;
            else
                mrow.rec.setValue(idx, record.value(i));
        }
        return isOk; }
    }
    return false;
}
Example #20
0
void CStudentManage::slotEditTextChanged(QString str)
{
    //如果为空,检索所有的字段
    if (str.isEmpty())
    {
        m_Model->setFilter("");
        m_Model->select();
    }

    QSqlRecord record = m_Model->record();
    QString ModelFilter;
    for (int i = 0; i < record.count(); ++i)
    {
        //获取字段名
        QString FilterName = record.fieldName(i);
        //如果是日期 直接跳过
        if (FilterName == "Birth" || FilterName == "Entrance_date")
            continue;
        if (i != 0)
        {
            ModelFilter += " or ";
        }
        //拼接
        QString subFilter = QObject::tr("%1 like '%%2%'").arg(FilterName.toUtf8().data(), str.toUtf8().data());
        //QString subFilter = QString().sprintf("%s like '%%%s%%'", FilterName.toUtf8().data(), str.toUtf8().data());

        ModelFilter += subFilter;
    }
    //qDebug() << ModelFilter;
    m_Model->setFilter(ModelFilter);
    m_Model->select();
}
T * DataMapper<Subclass, T, I>::getBy(const QString & whereClause)
{
    QSqlQuery query = getDatabase().build(SELECT("*").FROM(table()).WHERE(whereClause).LIMIT(1));

    if (query.exec())
    {
        QSqlRecord record = query.record();
        QMap<QString, int> indices;

        for (unsigned i = 0;i < record.count();++i)
        {
            indices[record.fieldName(i)] = i;
        }

        if (query.next())
        {
            QVariantMap map;

            for (QString fieldName : indices.keys())
            {
                map[fieldName] = query.value(indices[fieldName]);
            }

            return obtainFromIdentityMap(map);
        }
    }

    return nullptr;
}
Example #22
0
bool SqlQueryWriter::serialize(const QString & filePath)
{
    QFile file(filePath);
    if (!file.open(QFile::WriteOnly))
        return false;
    QTextStream stream(&file);
    stream.setCodec("UTF-8");

    QSqlRecord record = mQuery.record();
    for(int i=0; i<record.count(); i++)
    {
        stream << "\"" << record.fieldName( i ) << "\"";
        if( i != record.count() -1 )
            stream << ",";
    }
    stream << "\n";

    mQuery.first();
    mQuery.previous();

    while( mQuery.next() )
    {
        for(int i=0; i<record.count(); i++)
        {
            stream << "\"" << mQuery.value(i).toString().replace("\"","\"\"") << "\"";
            if( i != record.count() -1 )
                stream << ",";
        }
        stream << "\n";
    }

    return true;
}
Example #23
0
QStringList DatabaseDescriptor::getColumns(const QString &tableName) {
    QStringList result;
    QSqlRecord columns = QcDatabase::getInstance()->getDatabase().record(tableName);
    for(int i=0;i<columns.count();i++) {
        result.append(columns.fieldName(i));
    }
    return result;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  update account infor line edits when currentItem changes
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void MainWindow::on_accountList_itemClicked(QListWidgetItem *item)
{
    //update linedits with information when they are clicked in the list widget

    //first linedit is easy we already have the decrypted text
    ui->accountEdit->setText(item->text());
    
    //open database
    QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
    db.setDatabaseName( "users.db3" );
    if( !db.open() )
    {
      qDebug() << db.lastError();
      qFatal( "Failed to connect." );
    }

    //look for username in the users table
    QSqlQuery qry;
    QString queryString = "SELECT * FROM '" + QString::fromStdString(encryption::encrypt(username,29,41)) + "' WHERE username='******'";\
    qDebug() << queryString;
    qry.prepare(queryString);

    if( !qry.exec() )
      qDebug() << qry.lastError();
    else
    {   
        qDebug( "entry Selected!" );

        QSqlRecord rec = qry.record();

        int cols = rec.count();

        for( int c=0; c<cols; c++ )
            qDebug() << QString( "Column %1: %2" ).arg( c ).arg( rec.fieldName(c) );

        for( int r=0; qry.next(); r++ )
        {
            ui->passEdit->setText(QString::fromStdString(encryption::decrypt(qry.value(1).toString().toStdString(), 29, 41)));
            for( int c=0; c<cols; c++ )
            {
                qDebug() << QString( "Row %1, %2: %3" ).arg( r ).arg( rec.fieldName(c) ).arg( qry.value(c).toString() );
            }//for
        }//for
    }
    db.close();
}
SummarizeTableDialog::SummarizeTableDialog(const QSqlRecord &record, QWidget *parent, Qt::WindowFlags f) :
    QDialog(parent, f), ui(new Ui::SummarizeTableDialog)
{
    ui->setupUi(this);
    for (int i=0; i<record.count(); i++)
    {
        allColumnNames << record.fieldName(i);
        if ((record.field(i).type()==QVariant::Double)||
            (record.field(i).type()==QVariant::Int))
        {
            numericColumnNames << record.fieldName(i);
        }
    }
    ui->rowComboBox->addItems(allColumnNames);
    ui->columnComboBox->addItems(allColumnNames);
    ui->valueComboBox->addItems(allColumnNames);
    connect(ui->summarizeRadioBtn, SIGNAL(toggled(bool)), this, SLOT(summarizeEnabled(bool)));
}
Example #26
0
QVariant QueryModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole && !this->records.isEmpty()) {
        QSqlRecord r = this->records.at(0);
        return r.fieldName(section);
    }

    return QVariant();
}
Example #27
0
QString DbFunc::csvHeader(const QSqlQuery& query, const char sep)
{
    QSqlRecord record = query.record();
    int nfields = record.count();
    QStringList fieldnames;
    for (int i = 0; i < nfields; ++i) {
        fieldnames.append(record.fieldName(i));
    }
    return fieldnames.join(sep);
}
ChartSettingsDialog::ChartSettingsDialog(const QSqlRecord &record, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ChartSettingsDialog)
{
    ui->setupUi(this);
    connect(ui->yAxisColumnComboBox, SIGNAL(currentIndexChanged(QString)),
            this, SIGNAL(yValuesColumnChanged(QString)));
    for (int i=0; i<record.count(); i++)
    {
        allColumnNames << record.fieldName(i);
        if ((record.field(i).type()==QVariant::Double)||
                (record.field(i).type()==QVariant::Int))
        {
            numericColumnNames << record.fieldName(i);
        }
    }
    ui->xAxisColumnComboBox->addItems(allColumnNames);
    ui->yAxisColumnComboBox->addItems(numericColumnNames);
}
Example #29
0
QString Logger::infoLog(const QSqlRecord &record) const
{
    QString info;
    for(int i=0; i<record.count(); i++){
        info.append(QString("%1:%2|")
                    .arg(record.fieldName(i))
                    .arg(record.value(i).toString()));
    }
    return info;
}
Example #30
0
void DCredencial::accept()
{
    if( this->equipo.isEmpty() || this->id_equipo == -1 ) {
        qDebug( "Equipo no seteado" ); return;
    }
    // Verificaciones
    if( this->LEMedio->text().isEmpty() ) {
        QMessageBox::warning( this, "Error", "Por favor ingrese un medio para esta credencial" );
        return;
    }
    if( this->LENombre->text().isEmpty() ) {
        QMessageBox::warning( this, "Error", "Por favor ingrese un Nombre para esta credencial" );
        return;
    }
    if( this->LEDNI->text().isEmpty() ) {
        QMessageBox::warning( this, "Error", "Por favor ingrese un DNI para esta credencial" );
        return;
    }
    if( !this->CkBAcc1->isChecked() && !this->CkBAcc2->isChecked() && !this->CkBAcc3->isChecked() && !this->CkBAcc4->isChecked() && !this->CkBAcc5->isChecked() && !this->CkBAcc6->isChecked()) {
        QMessageBox::warning( this, "Error", "Por favor, elija un nivel de acceso para esta credencial" );
        return;
    }
    // Guardo el registro
    QSqlRecord rec = this->modelo->record();
    //rec.remove( 0 );
    rec.setValue( 1, this->id_equipo );
    rec.setValue( "nombre", this->LENombre->text() );
    rec.setValue( "dni", this->LEDNI->text() );
    rec.setValue( "medio", this->LEMedio->text() );
    rec.setValue( "acc1", this->CkBAcc1->isChecked() );
    rec.setValue( "acc2", this->CkBAcc2->isChecked() );
    rec.setValue( "acc3", this->CkBAcc3->isChecked() );
    rec.setValue( "acc4", this->CkBAcc4->isChecked() );
    rec.setValue( "acc5", this->CkBAcc5->isChecked() );
    rec.setValue( "acc6", this->CkBAcc6->isChecked() );
    for( int i = 0; i< rec.count(); i++ ) {
        qDebug( QString( "%1: %2 - %3" ).arg( i ).arg( rec.fieldName( i ) ).arg( rec.value( i ).toString() ).toLocal8Bit() );
    }
    if( this->modelo->insertRecord( -1, rec ) ) {
        int id_rec = this->modelo->query().lastInsertId().toInt();
        // imprimo la tarjeta
        ParameterList lista;
        lista.append( Parameter( "id_credencial", id_rec ) );
        if( this->reporte->hacer( lista ) ) {
            QMessageBox::information( this, "listo", QString("Credencial #%1 creada e impresa correctamente" ).arg( QString::number( id_rec, 'g', 6 ) ) );
            this->limpiarDatos();
        } else {
            qDebug( "No se pudo realizar el reporte" );
        }
    } else {
        qDebug( "Error al insertar los datos" );
        qDebug( this->modelo->lastError().text().toLocal8Bit() );
    }
}