本文整理汇总了C++中QSqlRecord::fieldName方法的典型用法代码示例。如果您正苦于以下问题:C++ QSqlRecord::fieldName方法的具体用法?C++ QSqlRecord::fieldName怎么用?C++ QSqlRecord::fieldName使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QSqlRecord
的用法示例。
在下文中一共展示了QSqlRecord::fieldName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: setData
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;
}
}
示例2: exportTableAsCSV
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;
}
示例3: record
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);
}
示例4: updateAccountList
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// 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);
}
示例5: tableChanged
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);
}
}
示例6: replaceCacheRecordByServerRecord
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;
}
示例7: getQueryData
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;
}
示例8: getSingleQueryValue
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;
}
示例9: query
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;
}
示例10: insert
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());
}
示例11: query
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;
}
示例12: setRecord
/*! \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;
}
示例13: getDatabase
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;
}
示例14: agregarServicio
/*!
\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;
}
}
示例15: fieldName
QString QSqlRecordProto::fieldName(int index) const
{
QSqlRecord *item = qscriptvalue_cast<QSqlRecord*>(thisObject());
if (item)
return item->fieldName(index);
return QString();
}