void DatabaseManager::AddRow() { int rowNum = mptableModel->rowCount();//获得表的行数 QSqlRecord record = mptableModel->record(); QSqlField fieldStr("ReplaceString", QVariant::Char); QSqlField fieldRes("ReplaceRes", QVariant::Char); QSqlField fieldPak("ReplacePak", QVariant::Char); QSqlField fieldAppPak("ReplaceAppPak", QVariant::Char); fieldStr.setValue(QStringLiteral("双击编辑")); fieldRes.setValue(QStringLiteral("双击编辑")); fieldPak.setValue(QStringLiteral("双击编辑")); fieldAppPak.setValue(QStringLiteral("双击编辑")); record.append(fieldStr); record.append(fieldRes); record.append(fieldPak); record.append(fieldAppPak); if (!mptableModel->insertRecord(rowNum, record)){ BjMessageBox::warning(NULL, QStringLiteral("数据库错误"), QStringLiteral("数据库错误: %1").arg(mptableModel->lastError().text()), QMessageBox::Ok, QMessageBox::NoButton); mptableModel->revertAll();//如果不删除,则撤销 return; } if (!mptableModel->submitAll()){ BjMessageBox::warning(NULL, QStringLiteral("数据库错误"), QStringLiteral("数据库错误: %1").arg(mptableModel->lastError().text())); mptableModel->revertAll();//如果不删除,则撤销 } }
void Gconsignaciones::AddDasignar(){ mensajebox *add = new mensajebox("Guardar", "Esta seguro de guardar los datos?", this); int accepted = add->exec(); if (accepted == 1) { QSqlRecord record; QSqlField f1("Id_asig", QVariant::Int); QSqlField f2("Id_pro", QVariant::Int); QSqlField f3("Cantidad", QVariant::Int); QSqlField f4("Costo", QVariant::Double); total =total+(ui->costo2spinbox->value()*ui->cantidad2->value()); f1.setValue(QVariant(idunicoasignar)); f2.setValue(QVariant(ui->id2spinbox->text().toInt(0, 10))); f3.setValue(QVariant(ui->cantidad2->value())); f4.setValue(QVariant(ui->costo2spinbox->value()*ui->cantidad2->value())); record.append(f1); record.append(f2); record.append(f3); record.append(f4); ui->total2->setValue(total);; modelodasignar->insertRecord(-1, record); ui->informacionproductoadicionado->show(); } }
bool DailymotionAccountModel::addAccount(const QString &userId, const QString &username, const QString &accessToken, const QString &refreshToken, const QString &scopes) { QSqlField userIdField("userId", QVariant::String); userIdField.setValue(userId); QSqlField usernameField("username", QVariant::String); usernameField.setValue(username); QSqlField accessTokenField("accessToken", QVariant::String); accessTokenField.setValue(accessToken); QSqlField refreshTokenField("refreshToken", QVariant::String); refreshTokenField.setValue(refreshToken); QSqlField scopesField("scopes", QVariant::String); scopesField.setValue(scopes); QSqlRecord record; record.append(userIdField); record.append(usernameField); record.append(accessTokenField); record.append(refreshTokenField); record.append(scopesField); if (insertRecord(-1, record)) { Dailymotion::instance()->setUserId(userId); const int count = rowCount(); emit dataChanged(index(0, 0), index(count - 1, columnCount() - 1)); emit countChanged(count); return true; } return false; }
void TargetsDialog::createTargetFromSelection() { if (StelApp::getInstance().getStelObjectMgr().getWasSelected()) { QList<StelObjectP> selectedObjects = StelApp::getInstance().getStelObjectMgr().getSelectedObject(); QListIterator<StelObjectP> objectIterator(selectedObjects); StelCore* core = StelApp::getInstance().getCore(); while (objectIterator.hasNext()) { StelObjectP stelObject = objectIterator.next(); QString type = stelObject->getType(); QString englishName = stelObject->getEnglishName(); if (englishName == "") { englishName = "No Name"; } float magnatude = stelObject->getVMagnitude(core); double angularSize = stelObject->getAngularSize(core); Vec3d pos; double ra, dec; // ra/dec in J2000 pos = stelObject->getJ2000EquatorialPos(core); StelUtils::rectToSphe(&ra, &dec, pos); QSqlField field1("name", QVariant::String); QSqlField field2("right_ascension", QVariant::Double); QSqlField field3("declination", QVariant::Double); QSqlField field4("target_type_id", QVariant::Int); QSqlField field5("magnitude", QVariant::Double); QSqlField field6("size", QVariant::Double); field1.setValue(QVariant(englishName)); field2.setValue(QVariant(ra)); field3.setValue(QVariant(dec)); field4.setValue(QVariant(1)); field5.setValue(QVariant(magnatude)); field6.setValue(QVariant(angularSize)); QSqlRecord newRecord = QSqlRecord(); newRecord.append(field1); newRecord.append(field2); newRecord.append(field3); newRecord.append(field4); newRecord.append(field5); newRecord.append(field6); if (tableModel->insertRecord(-1, newRecord)) { ui->targetsListView->setCurrentIndex(tableModel->index(tableModel->rowCount() - 1, 1)); } else { qWarning() << "LogBook: could not insert new target. The error is: " << tableModel->lastError(); } } } else { qDebug() << "====> Nothing selected."; } }
QSqlRecord DatabaseLayout::formatRecord(const LoggingEvent &rEvent) { QSqlField field; QSqlRecord record; if (!mTimeStamp.isEmpty()) { field.setName(mTimeStamp); field.setType(QVariant::DateTime); field.setGenerated(true); field.setValue(DateTime::fromMSecsSinceEpoch(rEvent.timeStamp())); record.append(field); } if (!mLoggerName.isEmpty()) { field.setName(mLoggerName); field.setType(QVariant::String); field.setGenerated(true); field.setValue(rEvent.loggerName()); record.append(field); } if (!mThreadName.isEmpty()) { field.setName(mThreadName); field.setType(QVariant::String); field.setGenerated(true); field.setValue(rEvent.threadName()); record.append(field); } if (!mLevel.isEmpty()) { field.setName(mLevel); field.setType(QVariant::String); field.setGenerated(true); field.setValue(rEvent.level().toString()); record.append(field); } if (!mMessage.isEmpty()) { field.setName(mMessage); field.setType(QVariant::String); field.setGenerated(true); field.setValue(rEvent.message()); record.append(field); } return record; }
// ## See if DELETE+INSERT is the best approach. Sqlite3 supports INSERT OR IGNORE which could aslo be used // ## Also check other upsert methods QList<QSqlRecord> VideoParser::updateMediaInfos(const QList<QFileInfo> &fis, const QString &searchPath, QSqlDatabase db) { Q_UNUSED(searchPath); QList<QSqlRecord> records; QSqlQuery query(db); ScopedTransaction transaction(db); foreach(const QFileInfo &fi, fis) { DEBUG << "Updating " << fi.absoluteFilePath(); query.prepare("DELETE FROM video WHERE filepath=:filepath"); query.bindValue(":filepath", fi.absoluteFilePath()); if (!query.exec()) qWarning() << query.lastError().text(); if (!query.prepare("INSERT INTO video (filepath, title, thumbnail, uri, directory, mtime, ctime, filesize, show, season) " " VALUES (:filepath, :title, :thumbnail, :uri, :directory, :mtime, :ctime, :filesize, :show, :season)")) { qWarning() << query.lastError().text(); return records; } query.bindValue(":filepath", fi.absoluteFilePath()); query.bindValue(":title", determineTitle(fi)); query.bindValue(":thumbnail", generateThumbnail(m_settings, fi)); query.bindValue(":uri", QUrl::fromLocalFile(fi.absoluteFilePath()).toEncoded()); query.bindValue(":directory", fi.absolutePath() + '/'); query.bindValue(":mtime", fi.lastModified().toTime_t()); query.bindValue(":ctime", fi.created().toTime_t()); query.bindValue(":filesize", fi.size()); QPair<QString, QString> showAndSeason = determineShowAndSeason(fi, searchPath); query.bindValue(":show", showAndSeason.first); query.bindValue(":season", showAndSeason.second); if (!query.exec()) qWarning() << query.lastError().text(); QSqlRecord record; record.append(QSqlField("id", QVariant::Int)); record.setValue(0, query.lastInsertId()); QMap<QString, QVariant> boundValues = query.boundValues(); for (QMap<QString, QVariant>::const_iterator it = boundValues.constBegin(); it != boundValues.constEnd(); ++it) { QString key = it.key().mid(1); // remove the ':' record.append(QSqlField(key, (QVariant::Type) it.value().type())); record.setValue(key, it.value()); } records.append(record); }
void SupplierDlg::accept() { if(le_name->text().trimmed().isEmpty() || !cb_area->currentIndex()) { QMessageBox::information(this, trUtf8("Alta Proveedor"), trUtf8("Debe llenar al menos los campos obligatorios.")); le_name->setFocus(); return; } if(selectedRow >= 0) { mapper->submit(); } else { QSqlRecord record; QSqlField nameField("name", QVariant::String); QSqlField areaField("idArea", QVariant::Int); QSqlField addressField("address", QVariant::String); QSqlField locationField("location", QVariant::String); QSqlField phoneField("phone", QVariant::String); QSqlField faxField("fax", QVariant::String); QSqlField emailField("email", QVariant::String); QSqlField contactNameField("contactName", QVariant::String); QSqlField contactPhoneField("contactPhone", QVariant::String); int idA = cb_area->model()->data(cb_area->model()->index( cb_area->currentIndex(), 0)).toInt(); nameField.setValue(le_name->text()); areaField.setValue(idA); addressField.setValue(le_address->text()); locationField.setValue(le_location->text()); phoneField.setValue(le_phone->text()); faxField.setValue(le_fax->text()); emailField.setValue(le_email->text()); contactNameField.setValue(le_contactName->text()); contactPhoneField.setValue(le_contactPhone->text()); record.append(nameField); record.append(areaField); record.append(addressField); record.append(locationField); record.append(phoneField); record.append(faxField); record.append(emailField); record.append(contactNameField); record.append(contactPhoneField); if(!model->insertRecord(-1, record)) { model->revertAll(); if(errorCommon(this, SUPPLIER_WINDOW, model->lastError().number())) { return; } } } QDialog::accept(); }
bool SoundCloudAccountModel::addAccount(const QString &userId, const QString &username, const QString &accessToken, const QString &refreshToken, const QString &scopes) { Logger::log(QString("SoundCloudAccountModel::addAccount(). User ID: %1, Username: %2, Access token: %3, Refresh token: %4, Scopes: %5").arg(userId).arg(username).arg(accessToken).arg(refreshToken).arg(scopes), Logger::LowVerbosity); QSqlField userIdField("userId", QVariant::String); userIdField.setValue(userId); QSqlField usernameField("username", QVariant::String); usernameField.setValue(username); QSqlField accessTokenField("accessToken", QVariant::String); accessTokenField.setValue(accessToken); QSqlField refreshTokenField("refreshToken", QVariant::String); refreshTokenField.setValue(refreshToken); QSqlField scopesField("scopes", QVariant::String); scopesField.setValue(scopes); QSqlRecord record; record.append(userIdField); record.append(usernameField); record.append(accessTokenField); record.append(refreshTokenField); record.append(scopesField); const int count = rowCount(); for (int i = 0; i < count; i++) { if (data(index(i, 0)) == userId) { if (setRecord(i, record)) { SoundCloud::setUserId(userId); return true; } return false; } } if (insertRecord(-1, record)) { SoundCloud::setUserId(userId); const int count = rowCount(); emit dataChanged(index(0, 0), index(count - 1, columnCount() - 1)); emit countChanged(count); return true; } return false; }
void SQLiteResultPrivate::initColumns(bool emptyResultset) { int nCols = sqlite3_column_count(stmt); if (nCols <= 0) return; q->init(nCols); for (int i = 0; i < nCols; ++i) { QString colName = stringFromUnicode(reinterpret_cast<const QChar *>( sqlite3_column_name16(stmt, i)) ).remove(QLatin1Char('"')); // must use typeName for resolving the type to match SQLiteDriver::record QString typeName = stringFromUnicode(reinterpret_cast<const QChar *>( sqlite3_column_decltype16(stmt, i))); int dotIdx = colName.lastIndexOf(QLatin1Char('.')); QSqlField fld(colName.mid(dotIdx == -1 ? 0 : dotIdx + 1), qGetColumnType(typeName)); // sqlite3_column_type is documented to have undefined behavior if the result set is empty int stp = emptyResultset ? -1 : sqlite3_column_type(stmt, i); fld.setSqlType(stp); rInf.append(fld); } }
QSqlRecord QPSQLResult::record() const { QSqlRecord info; if (!isActive() || !isSelect()) return info; int count = PQnfields(d->result); for (int i = 0; i < count; ++i) { QSqlField f; if (d->driver->isUtf8) f.setName(QString::fromUtf8(PQfname(d->result, i))); else f.setName(QString::fromLocal8Bit(PQfname(d->result, i))); f.setType(qDecodePSQLType(PQftype(d->result, i))); int len = PQfsize(d->result, i); int precision = PQfmod(d->result, i); // swap length and precision if length == -1 if (len == -1 && precision > -1) { len = precision - 4; precision = -1; } f.setLength(len); f.setPrecision(precision); f.setSqlType(PQftype(d->result, i)); info.append(f); } return info; }
// called on first fetch void QSQLite2ResultPrivate::init(const char **cnames, int numCols) { if (!cnames) return; rInf.clear(); if (numCols <= 0) return; q->init(numCols); for (int i = 0; i < numCols; ++i) { const char* lastDot = strrchr(cnames[i], '.'); const char* fieldName = lastDot ? lastDot + 1 : cnames[i]; //remove quotations around the field name if any QString fieldStr = QString::fromAscii(fieldName); QLatin1Char quote('\"'); if ( fieldStr.length() > 2 && fieldStr.startsWith(quote) && fieldStr.endsWith(quote)) { fieldStr = fieldStr.mid(1); fieldStr.chop(1); } rInf.append(QSqlField(fieldStr, nameToType(QString::fromAscii(cnames[i+numCols])))); } }
void CustomerDlg::accept() { if(le_lastName->text().trimmed().isEmpty()) { QMessageBox::information(this, trUtf8("Datos incompletos"), trUtf8("Debe llenar al menos los campos obligatorios.")); le_lastName->setFocus(); return; } if(selectedRow >= 0) { mapper->submit(); } else { QSqlRecord rec; QSqlField lastNameFiel("lastName", QVariant::String); QSqlField nameField("name", QVariant::String); QSqlField addressField("address", QVariant::String); QSqlField locationField("location", QVariant::String); QSqlField cellPoneField("cellphone", QVariant::String); QSqlField phoneField("phone", QVariant::String); QSqlField emailField("email", QVariant::String); lastNameFiel.setValue(le_lastName->text()); nameField.setValue(le_name->text()); addressField.setValue(le_address->text()); locationField.setValue(le_location->text()); cellPoneField.setValue(le_cellphone->text()); phoneField.setValue(le_phone->text()); emailField.setValue(le_email->text()); rec.append(lastNameFiel); rec.append(nameField); rec.append(addressField); rec.append(locationField); rec.append(cellPoneField); rec.append(phoneField); rec.append(emailField); if(!model->insertRecord(-1, rec)) { model->revertAll(); if(errorCommon(this, CUSTOMER_WINDOW, model->lastError().number())) return; } } QDialog::accept(); }
void AddContactDialog::onAccepted() { QSqlRecord record; QSqlField f1("firstname",QVariant::String); QSqlField f2("lastname",QVariant::String); QSqlField f3("birthday",QVariant::String); f1.setValue(QVariant(ui->firstNameEdit->text())); f2.setValue(QVariant(ui->lastNameEdit->text())); f3.setValue(QVariant(ui->birthdayEdit->text())); record.append(f1); record.append(f2); record.append(f3); // model->insertRecord(-1,record); model->insertRecord(0,record); }
void BarlowsDataMapper::insertNewBarlow() { QSqlField field1("model", QVariant::String); QSqlField field2("vendor", QVariant::String); QSqlField field3("factor", QVariant::Double); field1.setValue(QVariant("Model")); field2.setValue(QVariant("Vendor")); field3.setValue(QVariant(1.0)); QSqlRecord newRecord = QSqlRecord(); newRecord.append(field1); newRecord.append(field2); newRecord.append(field3); if (tableModel->insertRecord(-1, newRecord)) { widget->barlowsListView->setCurrentIndex(tableModel->index(tableModel->rowCount() - 1, 1)); } else { qWarning() << "LogBook: could not insert new barlow. The error is: " << tableModel->lastError(); } }
void ModuloUsuarios::createPermisoRec(int & idusr, int & idMod,QSqlRecord & rcd) { QSqlField f1("idcolaborador", QVariant::Int); QSqlField f2("id_sys_modulo", QVariant::Int); QSqlField f3("id_modulo", QVariant::Int); QSqlField f4("acceso",QVariant::Int); QSqlField f5("fecha",QVariant::DateTime); f1.setValue(QVariant(idusr)); f2.setValue(QVariant(idMod)); f3.setValue(QVariant(idMod)); f4.setValue(QVariant(0)); f5.clear(); rcd.append(f1); rcd.append(f2); rcd.append(f3); rcd.append(f4); rcd.append(f5); }
/** * Get table information. * @param tableName * @return */ QSqlRecord KQPostgreSqlDriver::record(const QString &tableName) const { QSqlRecord info; if (! isOpen()) { return info; } QString table(tableName.toLower()), schema; splitSchemaName(table, schema); QString stmt("select pg_attribute.attname, pg_attribute.atttypid::int, " "pg_attribute.attnotnull, pg_attribute.attlen, pg_attribute.atttypmod, " "pg_attrdef.adsrc " "from pg_class, pg_attribute " "left join pg_attrdef on (pg_attrdef.adrelid = " "pg_attribute.attrelid and pg_attrdef.adnum = pg_attribute.attnum) " "where %1 " "and pg_class.relname = '%2' " "and pg_attribute.attnum > 0 " "and pg_attribute.attrelid = pg_class.oid " "and pg_attribute.attisdropped = false " "order by pg_attribute.attnum "); if (schema.isEmpty()) { stmt = stmt.arg(QString("pg_table_is_visible(pg_class.oid)")); } else { stmt = stmt.arg(QString::fromLatin1("pg_class.relnamespace = (select oid from " "pg_namespace where pg_namespace.nspname = '%1')").arg(schema)); } stmt = stmt.arg(table); QSqlQuery query(createResult()); if (! query.exec(stmt)) { // If can not execute statement then return an empty record. return info; } while (query.next()) { int len = query.value(3).toInt(); int precision = query.value(4).toInt(); // swap length and precision if length == -1 if (len == -1 && precision > -1) { len = precision - 4; precision = -1; } QString defVal = query.value(5).toString(); if (!defVal.isEmpty() && defVal.at(0) == QLatin1Char('\'')) defVal = defVal.mid(1, defVal.length() - 2); QSqlField f(query.value(0).toString(), KQPostgreSqlResult::variantTypeFromPostgreType(query.value(1).toInt())); f.setRequired(query.value(2).toBool()); f.setLength(len); f.setPrecision(precision); f.setDefaultValue(defVal); f.setSqlType(query.value(1).toInt()); info.append(f); } return info; }
void ContactPanel::onAddScopeClicked() { int rowCount = m_trustScopeModel->rowCount(); QSqlRecord record; QSqlField identityField("contact_namespace", QVariant::String); record.append(identityField); record.setValue("contact_namespace", m_currentSelectedContact); m_trustScopeModel->insertRow(rowCount); m_trustScopeModel->setRecord(rowCount, record); }
void Gconsignaciones::Addasignar(){ mensajebox *add = new mensajebox("Guardar", "Esta seguro de guardar los datos?", this); int accepted = add->exec(); if (accepted == 1) { QSqlRecord record; QSqlField f1("Id_asig", QVariant::Int); QSqlField f2("Estado", QVariant::String); QSqlField f3("Fecha", QVariant::Date); QSqlField f4("Total", QVariant::Double); QSqlField f5("Id_con", QVariant::Int); QSqlQueryModel idunicomodel; QString selec="SELECT Id_con FROM Consignatario where (Nombre='"+ui->consignatariocombo2->currentText()+"')"; idunicomodel.setQuery(selec); int consignatarioid=idunicomodel.record(0).value("Id_con").toInt(); QString estado=""; if(ui->realizadoradio->isChecked()==true) { estado=ui->realizadoradio->text(); }else{ estado=ui->pendienteradio->text(); } f1.setValue(QVariant(idunicoasignar)); f2.setValue(QVariant(estado)); f3.setValue(QVariant(QDate::currentDate())); f4.setValue(QVariant(total)); f5.setValue(QVariant(consignatarioid)); record.append(f1); record.append(f2); record.append(f3); record.append(f4); record.append(f5); model->insertRecord(-1, record); total=0; ui->informaciondasignaradicionado->show(); ui->dasignarw->setCurrentIndex(2); } }
int Dialog::addNewArtist(const QString &name) { QSqlTableModel *artistModel = model->relationModel(2); QSqlRecord record; int id = generateArtistId(); QSqlField f1("id", QVariant::Int); QSqlField f2("artist", QVariant::String); QSqlField f3("albumcount", QVariant::Int); f1.setValue(QVariant(id)); f2.setValue(QVariant(name)); f3.setValue(QVariant(0)); record.append(f1); record.append(f2); record.append(f3); artistModel->insertRecord(-1, record); return id; }
void ContextModel::addNewContext(QString newContext) { if (newContext.isEmpty()) { return; } QSqlQuery query; query.prepare("select count(id) from context where shortdescr like :context"); query.bindValue(":context", newContext); query.exec(); if (query.next()) { if (query.record().value("count(id)").toInt() > 0) return; } qDebug() << "save new context " << newContext << " in database."; QSqlRecord record; QSqlField shortDescr = QSqlField("shortdescr", QVariant::String); shortDescr.setValue(newContext); record.append(shortDescr); QSqlField id = QSqlField("id", QVariant::Int); shortDescr.setValue(20); record.append(id); if(!insertRecord( -1, record)) { qDebug("could not create new context."); } if (!submitAll()) { qDebug("could not create new context."); } select(); }
void TargetsDialog::insertNewTarget() { QSqlField field1("name", QVariant::String); QSqlField field3("right_ascension", QVariant::Double); QSqlField field4("declination", QVariant::Double); QSqlField field6("target_type_id", QVariant::Int); field1.setValue(QVariant("name")); field3.setValue(QVariant(0.0)); field4.setValue(QVariant(0.0)); field6.setValue(QVariant(1)); QSqlRecord newRecord = QSqlRecord(); newRecord.append(field1); newRecord.append(field3); newRecord.append(field4); newRecord.append(field6); if (tableModel->insertRecord(-1, newRecord)) { ui->targetsListView->setCurrentIndex(tableModel->index(tableModel->rowCount() - 1, 1)); } else { qWarning() << "LogBook: could not insert new target. The error is: " << tableModel->lastError(); } }
int Dialog::addNewAlbum(const QString &title, int artistId) { int id = generateAlbumId(); QSqlRecord record; QSqlField f1("albumid", QVariant::Int); QSqlField f2("title", QVariant::String); QSqlField f3("artistid", QVariant::Int); QSqlField f4("year", QVariant::Int); f1.setValue(QVariant(id)); f2.setValue(QVariant(title)); f3.setValue(QVariant(artistId)); f4.setValue(QVariant(yearEditor->value())); record.append(f1); record.append(f2); record.append(f3); record.append(f4); model->insertRecord(-1, record); return id; }
void QSQLiteResultPrivate::initColumns(bool emptyResultset) { int nCols = sqlite3_column_count(stmt); if (nCols <= 0) return; q->init(nCols); for (int i = 0; i < nCols; ++i) { QString colName = QString(reinterpret_cast<const QChar *>( sqlite3_column_name16(stmt, i)) ).remove(QLatin1Char('"')); // must use typeName for resolving the type to match QSqliteDriver::record QString typeName = QString(reinterpret_cast<const QChar *>( sqlite3_column_decltype16(stmt, i))); // sqlite3_column_type is documented to have undefined behavior if the result set is empty int stp = emptyResultset ? -1 : sqlite3_column_type(stmt, i); QVariant::Type fieldType; if (!typeName.isEmpty()) { fieldType = qGetColumnType(typeName); } else { // Get the proper type for the field based on stp value switch (stp) { case SQLITE_INTEGER: fieldType = QVariant::Int; break; case SQLITE_FLOAT: fieldType = QVariant::Double; break; case SQLITE_BLOB: fieldType = QVariant::ByteArray; break; case SQLITE_TEXT: fieldType = QVariant::String; break; case SQLITE_NULL: default: fieldType = QVariant::Invalid; break; } } int dotIdx = colName.lastIndexOf(QLatin1Char('.')); QSqlField fld(colName.mid(dotIdx == -1 ? 0 : dotIdx + 1), fieldType); fld.setSqlType(stp); rInf.append(fld); } }
QSqlRecord QMYSQLDriver::record( const QString& tablename ) const { QSqlRecord fil; if ( !isOpen() ) return fil; MYSQL_RES* r = mysql_list_fields( d->mysql, tablename.local8Bit().data(), 0); if ( !r ) { return fil; } MYSQL_FIELD* field; while ( (field = mysql_fetch_field( r ))) { QSqlField f ( QString( field->name ) , qDecodeMYSQLType( (int)field->type, field->flags ) ); fil.append ( f ); } mysql_free_result( r ); return fil; }
QSqlRecord DbSchema::sqlRecord(QObject *table, bool lowercase_field_names) { QSqlRecord ret; QQmlListReference fields(table, "fields", m_eventPlugin->qmlEngine()); for (int i = 0; i < fields.count(); ++i) { QObject *field = fields.at(i); QString name = field->property("name").toString(); if(lowercase_field_names) name = name.toLower(); QVariant typev = field->property("type"); QObject *type = typev.value<QObject*>(); QF_ASSERT(type != nullptr, "Internal error: Cannot get field type", return QSqlRecord()); QByteArray type_name = type->property("metaTypeName").toString().toLatin1(); QSqlField fld(name, QVariant::nameToType(type_name.constData())); ret.append(fld); //qfInfo() << type << "name:" << name << "type:" << type_name; } return ret; }
QSqlRecord QMYSQLDriver::record( const QSqlQuery& query ) const { QSqlRecord fil; if ( !isOpen() ) return fil; if ( query.isActive() && query.isSelect() && query.driver() == this ) { QMYSQLResult* result = (QMYSQLResult*)query.result(); QMYSQLResultPrivate* p = result->d; if ( !mysql_errno( p->mysql ) ) { for ( ;; ) { MYSQL_FIELD* f = mysql_fetch_field( p->result ); if ( f ) { QSqlField fi( QString((const char*)f->name), qDecodeMYSQLType( f->type, f->flags ) ); fil.append( fi ); } else break; } } mysql_field_seek( p->result, 0 ); } return fil; }
void QSymSQLResultPrivate::initColumns(QSqlRecord& rec) { int nCols = stmt.ColumnCount(); if (nCols <= 0) { q->setLastError(qMakeError(access, QCoreApplication::translate("QSymSQLResult", "Error retrieving column count"), QSqlError::UnknownError, nCols)); return; } for (int i = 0; i < nCols; ++i) { TPtrC cName; TInt err = stmt.ColumnName(i, cName); if (err != KErrNone) { q->setLastError(qMakeError(access, QCoreApplication::translate("QSymSQLResult", "Error retrieving column name"), QSqlError::UnknownError, err)); return; } QString colName = qt_TDesC2QString(cName); // must use typeName for resolving the type to match QSymSQLDriver::record TPtrC tName; TSqlColumnType decColType; err = stmt.DeclaredColumnType(i, decColType); if (err != KErrNone) { q->setLastError(qMakeError(access, QCoreApplication::translate("QSymSQLResult", "Error retrieving column type"), QSqlError::UnknownError, err)); return; } int dotIdx = colName.lastIndexOf(QLatin1Char('.')); QSqlField fld(colName.mid(dotIdx == -1 ? 0 : dotIdx + 1), qGetColumnType(decColType)); rec.append(fld); } }
QSqlRecord SqliteDriver::record(const QString &tablename) const { QSqlRecord fil; if (!isOpen() || !dataBase_) return fil; QDomDocument doc(tablename); QDomElement docElem; QString stream = db_->managerModules()->contentCached(tablename + ".mtd"); if (!FLUtil::domDocumentSetContent(doc, stream)) { #ifdef FL_DEBUG qWarning("FLManager : " + QApplication::tr("Error al cargar los metadatos para la tabla %1").arg(tablename)); #endif return record2(tablename); } docElem = doc.documentElement(); FLTableMetaData *mtd = db_->manager()->metadata(&docElem, true); if (!mtd) return record2(tablename); FLTableMetaData::FLFieldMetaDataList *fl = mtd->fieldList(); if (!fl) { delete mtd; return record2(tablename); } if (fl->isEmpty()) { delete mtd; return record2(tablename); } QStringList fieldsNames = QStringList::split(",", mtd->fieldsNames()); for (QStringList::Iterator it = fieldsNames.begin(); it != fieldsNames.end(); ++it) fil.append(QSqlField((*it), FLFieldMetaData::flDecodeType(mtd->fieldType((*it))))); delete mtd; return fil; }
QSqlRecord QTDSDriver::record(const QString& tablename) const { QSqlRecord info; if (!isOpen()) return info; QSqlQuery t(createResult()); t.setForwardOnly(true); QString table = tablename; if (isIdentifierEscaped(table, QSqlDriver::TableName)) table = stripDelimiters(table, QSqlDriver::TableName); QString stmt (QLatin1String("select name, type, length, prec from syscolumns " "where id = (select id from sysobjects where name = '%1')")); t.exec(stmt.arg(table)); while (t.next()) { QSqlField f(t.value(0).toString().simplified(), qDecodeTDSType(t.value(1).toInt())); f.setLength(t.value(2).toInt()); f.setPrecision(t.value(3).toInt()); f.setSqlType(t.value(1).toInt()); info.append(f); } return info; }
void UserDialog::addUser() { QSqlRecord record; QSqlField id("id", QVariant::Int); QSqlField username("username", QVariant::String); QSqlField email("email", QVariant::String); QSqlField hashedPassword("hashed_password", QVariant::String); QSqlField salt("salt", QVariant::String); QSqlField roleId("role_id", QVariant::Int); id.setAutoValue(true); username.setValue(QVariant(usernameLineEdit->text())); email.setValue(QVariant(emailLineEdit->text())); QString generatedSalt = QUuid::createUuid().toString(); QString generatedHashedPassword = QCryptographicHash::hash(passwordLineEdit->text().toAscii() + generatedSalt.toAscii(), QCryptographicHash::Sha1); hashedPassword.setValue(QVariant(generatedHashedPassword)); salt.setValue(QVariant(generatedSalt)); roleId.setValue(QVariant(getRoleId())); record.append(id); record.append(username); record.append(email); record.append(hashedPassword); record.append(salt); record.append(roleId); if(isFieldInputValid() && !isPasswordEmpty() && !userExists() && userModel->insertRecord(-1, record)) { accept(); } else { userModel->revertAll(); } }