本文整理汇总了C++中QSqlQuery::value方法的典型用法代码示例。如果您正苦于以下问题:C++ QSqlQuery::value方法的具体用法?C++ QSqlQuery::value怎么用?C++ QSqlQuery::value使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QSqlQuery
的用法示例。
在下文中一共展示了QSqlQuery::value方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: doImport
// ====================================================================================
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// IMPORT
// logFile, path_Dateiname, qsltype, rig, home_id
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void wadif::doImport(QString log,QString fpath, int qslmode, QString rig, int hId)
{
QString val, token, prog;
QString Call, qsoDate;
QString t, z;
int idx, n, oid, id, sekcnt, vl, len;
bool ok;
char buf[255];
sekcnt = 10; // Sekundenzähler 10..59
oid = 0;
QSqlQuery query;
QFile datei( fpath );
if(! datei.open(QIODevice::ReadOnly)) {
state = 1;
return; // FEHLER
}
count = 0;
QTextStream istream( &datei);
// Header lesen ----------------------------------
while( istream.atEnd() != true ) { // HEADER '<eoh>' suchen
len = 0;
while(len == 0) { // leere zeilen ueberspringen
t = istream.readLine(0);
len = t.count();
if(len != 0) break; // zeile mit text gefunden
}
idx = 0; // text auswerten
while(len != idx)
if(t[idx++] == QChar('<')) break; // suche '<'
z = "";
if(len != idx) { // '<' gefunden, text ist gueltig
while(t[idx] != QChar(':') && t[idx] != QChar('>')) z += t[idx++];
if(t[idx] == QChar('>')) { // '>' gefunden, dann ist token ohne text
z = z.toUpper(); // token immer groß
if(z.compare("EOH") == 0) break; // header_ende ?
}
else {
val = ""; // ':' gefunden, es gibt text
idx++;
if(z.compare("PROGRAMID") == 0) // wenn ProgrammID
while(t[idx] != QChar('>')) val += t[idx++];
vl = val.toInt(&ok,10);
idx++;
val = "";
n = vl; // text:_laenge
while(n-- != 0) val += t[idx++]; // text lesen
prog = val;
}
}
}
// Header gelesen
// ------------ jetzt DATA ---------------------
Error = "";
count = 0; // Datensatz Zähler
while(istream.atEnd() == FALSE) { // ADIF_text bis Datei_ende bearbeiten
i = 0;
while(i != qsoFields) strcpy(adh[i++].value,""); // value(datenfelder) QSO_tabelle loeschen
i = 0;
while(i != qslFields) strcpy(adhq[i++].value,""); // value(datenfelder) QSL_tabelle loeschen
i = 0;
while(i != awdFields) strcpy(adhw[i++].value,""); // value(datenfelder) AWD_tabelle loeschen
z = istream.readLine(0); // daten_zeile lesen und bearbeiten. Zeile ist: stream ohne '\n' or '\l\r',
// daten_token oder Zeilenanteile, daten_zeile_ende ist <eor> im stream.
if(z.compare("<EOF>") == 0) break; // File_ende ?
while(z.count() == 0) { // check: es koennte eine leer_zeile vor <eor> sein
if(istream.atEnd() == TRUE) break; // oder eine leer_zeile mitten in der text_zeile (Ucx)
z = istream.readLine(0); // suche text
}
if(istream.atEnd() == TRUE) break; // ok. ist File_ende
len = z.count();
vl = 0;
Lcn = "";
Cqz = "";
Ituz = "";
Dxcc = "";
t = "";
n = 0;
idx = 0; // zeilen_index
while( 1 ) { // 1. zeile aus datastream
while(len != idx) {
if(z[idx++] == QChar('<')) break; // gefunden
}
if(len == idx) { // das war eine leere_restzeile oder
z = istream.readLine(0); // zeile war token oder zeilen_anteil; neue zeile (token) lesen
len = z.count();
if(len == 0) // war leer_zeile
z = istream.readLine(0); // n. zeile lesen
len = z.count();
idx = 0;
//.........这里部分代码省略.........
示例2: saveDatabaseTimeRecord
bool DataManager::saveDatabaseTimeRecord(Map map) {
qDebug("DataManager::saveDatabaseTimeRecord");
QString userName;
#if defined(UNICODE)
if ( QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)
{
TCHAR winUserName[UNLEN + 1]; // UNLEN is defined in LMCONS.H
DWORD winUserNameSize = sizeof(winUserName);
GetUserName( winUserName, &winUserNameSize );
userName = QString::fromWCharArray( winUserName );
} else
#endif
{
char winUserName[UNLEN + 1]; // UNLEN is defined in LMCONS.H
DWORD winUserNameSize = sizeof(winUserName);
GetUserNameA( winUserName, &winUserNameSize );
userName = QString::fromLocal8Bit( winUserName );
}
qDebug("DataManager::saveDatabaseTimeRecord windows user: %s", userName.toStdString().c_str());
QString userGuid;
std::string userGuidSql = "select id from dbo.CoreUser where AccountName = 'VIS_BOG_HQ\\" + userName.toStdString() + "'";
QSqlQuery sqlUserGuid(QString(userGuidSql.c_str()));
if (sqlUserGuid.next()) {
userGuid = sqlUserGuid.value(0).toString();
qDebug("DataManager::saveDatabaseTimeRecord user guid: %s", userGuid.toStdString().c_str());
} else {
qDebug("User %s not found", userName.toStdString().c_str());
return false;
}
int periodId = period(map.date.toQDateTime());
qDebug("DataManager::saveDatabaseTimeRecord period id: %d", periodId);
if (periodId == -1) {
return false;
}
int displayOrder = 1;
QSqlQuery displayOrderSql;
if (displayOrderSql.prepare("select Max(displayOrder) from dbo.TimeEntry where PeriodId = :Period and CoreUserId = :CoreUserId")) {
displayOrderSql.bindValue(":Period", periodId);
displayOrderSql.bindValue(":CoreUserId", userGuid);
if (displayOrderSql.exec() && displayOrderSql.next()) {
displayOrder = displayOrderSql.value(0).toInt() + 1;
} else {
displayOrder = 1;
}
} else {
qDebug("Error getting the displayOrder");
return false;
}
qDebug("DataManager::saveDatabaseTimeRecord displayOrder: %d", displayOrder);
std::stringstream ssSql;
ssSql << "INSERT INTO TimeEntry (PeriodId,ProjectId,TaskId,CoreUserId,Date,Hours,Description,UpdatedOn,DisplayOrder,Version)";
ssSql << " VALUES (:PeriodId,:ProjectId,:TaskId,:CoreUserId,:Date,:Hours,:Description,:UpdatedOn,:DisplayOrder,:Version)";
QSqlQuery insert;
insert.prepare(QString(ssSql.str().c_str()));
insert.bindValue(":PeriodId", periodId);
insert.bindValue(":ProjectId", map.coreProject.id);
insert.bindValue(":TaskId", map.coreTask.id);
insert.bindValue(":CoreUserId", userGuid);
insert.bindValue(":Date", map.date.toQDateTime());
double minutes = ((double)((int)(map.time.totalMinutes() * 100))/(double)100);
insert.bindValue(":Hours", minutes);
insert.bindValue(":Description", map.description);
insert.bindValue(":UpdatedOn", QDateTime::currentDateTime());
insert.bindValue(":DisplayOrder", displayOrder);
insert.bindValue(":Version", 2);
bool updated = insert.exec();
if (!updated) {
qDebug("An error has ocurred executing the insertion. Error: %s", insert.lastError().text().toStdString().c_str());
}
qDebug("out DataManager::saveDatabaseTimeRecord");
return updated;
}
示例3: OpenDatabase
bool MSqlDatabase::OpenDatabase(bool skipdb)
{
if (!m_db.isValid())
{
LOG(VB_GENERAL, LOG_ERR,
"MSqlDatabase::OpenDatabase(), db object is not valid!");
return false;
}
bool connected = true;
if (!m_db.isOpen())
{
if (!skipdb)
m_dbparms = GetMythDB()->GetDatabaseParams();
m_db.setDatabaseName(m_dbparms.dbName);
m_db.setUserName(m_dbparms.dbUserName);
m_db.setPassword(m_dbparms.dbPassword);
m_db.setHostName(m_dbparms.dbHostName);
if (m_dbparms.dbHostName.isEmpty()) // Bootstrapping without a database?
{
connected = true; // Pretend to be connected
return true; // to reduce errors
}
if (m_dbparms.dbPort)
m_db.setPort(m_dbparms.dbPort);
// Prefer using the faster localhost connection if using standard
// ports, even if the user specified a DBHostName of 127.0.0.1. This
// will cause MySQL to use a Unix socket (on *nix) or shared memory (on
// Windows) connection.
if ((m_dbparms.dbPort == 0 || m_dbparms.dbPort == 3306) &&
m_dbparms.dbHostName == "127.0.0.1")
m_db.setHostName("localhost");
connected = m_db.open();
if (!connected && m_dbparms.wolEnabled)
{
int trycount = 0;
while (!connected && trycount++ < m_dbparms.wolRetry)
{
LOG(VB_GENERAL, LOG_INFO,
QString("Using WOL to wakeup database server (Try %1 of "
"%2)")
.arg(trycount).arg(m_dbparms.wolRetry));
if (myth_system(m_dbparms.wolCommand) != GENERIC_EXIT_OK)
{
LOG(VB_GENERAL, LOG_ERR,
QString("Failed to run WOL command '%1'")
.arg(m_dbparms.wolCommand));
}
sleep(m_dbparms.wolReconnect);
connected = m_db.open();
}
if (!connected)
{
LOG(VB_GENERAL, LOG_ERR,
"WOL failed, unable to connect to database!");
}
}
if (connected)
{
LOG(VB_GENERAL, LOG_INFO,
QString("Connected to database '%1' at host: %2")
.arg(m_db.databaseName()).arg(m_db.hostName()));
// WriteDelayed depends on SetHaveDBConnection() and SetHaveSchema()
// both being called with true, so order is important here.
GetMythDB()->SetHaveDBConnection(true);
if (!GetMythDB()->HaveSchema())
{
// We can't just check the count of QSqlDatabase::tables()
// because it returns all tables visible to the user in *all*
// databases (not just the current DB).
bool have_schema = false;
QString sql = "SELECT COUNT( "
" INFORMATION_SCHEMA.TABLES.TABLE_NAME "
" ) "
" FROM INFORMATION_SCHEMA.TABLES "
" WHERE INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA "
" = DATABASE() "
" AND INFORMATION_SCHEMA.TABLES.TABLE_TYPE = "
" 'BASE TABLE';";
// We can't use MSqlQuery to determine if we have a schema,
// since it will open a new connection, which will try to check
// if we have a schema
QSqlQuery query = m_db.exec(sql); // don't convert to MSqlQuery
if (query.next())
have_schema = query.value(0).toInt() > 1;
GetMythDB()->SetHaveSchema(have_schema);
}
GetMythDB()->WriteDelayedSettings();
}
//.........这里部分代码省略.........
示例4: f
Database::Database() {
QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"));
QSettings qs;
QStringList datapaths;
int i;
datapaths << g.qdBasePath.absolutePath();
#if QT_VERSION >= 0x050000
datapaths << QStandardPaths::writableLocation(QStandardPaths::DataLocation);
#else
datapaths << QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#endif
#if defined(Q_OS_UNIX) && ! defined(Q_OS_MAC)
datapaths << QDir::homePath() + QLatin1String("/.config/Mumble");
#endif
datapaths << QDir::homePath();
datapaths << QDir::currentPath();
datapaths << qApp->applicationDirPath();
datapaths << qs.value(QLatin1String("InstPath")).toString();
bool found = false;
for (i = 0; (i < datapaths.size()) && ! found; i++) {
if (!datapaths[i].isEmpty()) {
QFile f(datapaths[i] + QLatin1String("/mumble.sqlite"));
if (f.exists()) {
db.setDatabaseName(f.fileName());
found = db.open();
}
//TODO: If the above succeeds, but we also have a .mumble.sqlite, we open another DB!?
QFile f2(datapaths[i] + QLatin1String("/.mumble.sqlite"));
if (f2.exists()) {
db.setDatabaseName(f2.fileName());
found = db.open();
}
}
}
if (! found) {
for (i = 0; (i < datapaths.size()) && ! found; i++) {
if (!datapaths[i].isEmpty()) {
QDir::root().mkpath(datapaths[i]);
#ifdef Q_OS_WIN
QFile f(datapaths[i] + QLatin1String("/mumble.sqlite"));
#else
QFile f(datapaths[i] + QLatin1String("/.mumble.sqlite"));
#endif
db.setDatabaseName(f.fileName());
found = db.open();
}
}
}
if (! found) {
QMessageBox::critical(NULL, QLatin1String("Mumble"), tr("Mumble failed to initialize a database in any\nof the possible locations."), QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);
qFatal("Database: Failed initialization");
}
QFileInfo fi(db.databaseName());
if (! fi.isWritable()) {
QMessageBox::critical(NULL, QLatin1String("Mumble"), tr("The database '%1' is read-only. Mumble cannot store server settings (i.e. SSL certificates) until you fix this problem.").arg(Qt::escape(fi.filePath())), QMessageBox::Ok | QMessageBox::Default, QMessageBox::NoButton);
qWarning("Database: Database is read-only");
}
{
QFile f(db.databaseName());
f.setPermissions(f.permissions() & ~(QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup | QFile::ReadOther | QFile::WriteOther | QFile::ExeOther));
}
QSqlQuery query;
execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `servers` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `hostname` TEXT, `port` INTEGER DEFAULT " MUMTEXT(DEFAULT_MUMBLE_PORT) ", `username` TEXT, `password` TEXT)"));
query.exec(QLatin1String("ALTER TABLE `servers` ADD COLUMN `url` TEXT")); // Upgrade path, failing this query is not noteworthy
execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `comments` (`who` TEXT, `comment` BLOB, `seen` DATE)"));
execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `comments_comment` ON `comments`(`who`, `comment`)"));
execQueryAndLogFailure(query, QLatin1String("CREATE INDEX IF NOT EXISTS `comments_seen` ON `comments`(`seen`)"));
execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `blobs` (`hash` TEXT, `data` BLOB, `seen` DATE)"));
execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `blobs_hash` ON `blobs`(`hash`)"));
execQueryAndLogFailure(query, QLatin1String("CREATE INDEX IF NOT EXISTS `blobs_seen` ON `blobs`(`seen`)"));
execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `tokens` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB, `token` TEXT)"));
execQueryAndLogFailure(query, QLatin1String("CREATE INDEX IF NOT EXISTS `tokens_host_port` ON `tokens`(`digest`)"));
execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `shortcut` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB, `shortcut` BLOB, `target` BLOB, `suppress` INTEGER)"));
execQueryAndLogFailure(query, QLatin1String("CREATE INDEX IF NOT EXISTS `shortcut_host_port` ON `shortcut`(`digest`)"));
execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `udp` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `digest` BLOB)"));
execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `udp_host_port` ON `udp`(`digest`)"));
execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `cert` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hostname` TEXT, `port` INTEGER, `digest` TEXT)"));
execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `cert_host_port` ON `cert`(`hostname`,`port`)"));
execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `friends` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `hash` TEXT)"));
execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `friends_name` ON `friends`(`name`)"));
execQueryAndLogFailure(query, QLatin1String("CREATE UNIQUE INDEX IF NOT EXISTS `friends_hash` ON `friends`(`hash`)"));
execQueryAndLogFailure(query, QLatin1String("CREATE TABLE IF NOT EXISTS `ignored` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `hash` TEXT)"));
//.........这里部分代码省略.........
示例5: compareValues
bool OSArgumentRecord_Impl::compareValues(const QSqlQuery& query) const {
OS_ASSERT(query.isValid());
OS_ASSERT(query.isActive());
OS_ASSERT(query.isSelect());
bool result = ObjectRecord_Impl::compareValues(query);
QVariant value;
value = query.value(OSArgumentRecordColumns::rubyPerturbationRecordId);
if (value.isValid() && !value.isNull()) {
result = result && m_rubyMeasureRecordId && (*m_rubyMeasureRecordId == value.toInt());
}
else {
result = result && !m_rubyMeasureRecordId;
}
value = query.value(OSArgumentRecordColumns::rubyContinuousVariableRecordId);
if (value.isValid() && !value.isNull()) {
result = result && m_rubyContinuousVariableRecordId && (*m_rubyContinuousVariableRecordId == value.toInt());
}
else {
result = result && !m_rubyContinuousVariableRecordId;
}
value = query.value(OSArgumentRecordColumns::argumentType);
OS_ASSERT(value.isValid() && !value.isNull());
result = result && (m_argumentType == ruleset::OSArgumentType(value.toInt()));
value = query.value(OSArgumentRecordColumns::required);
OS_ASSERT(value.isValid() && !value.isNull());
result = result && (m_required == value.toBool());
value = query.value(OSArgumentRecordColumns::argumentValue);
if (value.isValid() && !value.isNull()) {
result = result && m_argumentValue && (m_argumentValue.get() == value.toString().toStdString());
}
else {
result = result && !m_argumentValue;
}
value = query.value(OSArgumentRecordColumns::defaultArgumentValue);
if (value.isValid() && !value.isNull()) {
result = result && m_defaultArgumentValue && (m_defaultArgumentValue.get() == value.toString().toStdString());
}
else {
result = result && !m_defaultArgumentValue;
}
value = query.value(OSArgumentRecordColumns::domainType);
OS_ASSERT(value.isValid() && !value.isNull());
result = result && (m_domainType == ruleset::OSDomainType(value.toInt()));
value = query.value(OSArgumentRecordColumns::domainValues);
if (value.isValid() && !value.isNull()) {
result = result && m_domain && (m_domain.get() == value.toString().toStdString());
}
else {
result = result && !m_domain;
}
value = query.value(OSArgumentRecordColumns::choices);
OS_ASSERT(value.isValid() && !value.isNull());
result = result && (m_choices == value.toString().toStdString());
value = query.value(OSArgumentRecordColumns::choiceDisplayNames);
OS_ASSERT(value.isValid() && !value.isNull());
result = result && (m_choiceDisplayNames == value.toString().toStdString());
value = query.value(OSArgumentRecordColumns::isRead);
OS_ASSERT(value.isValid() && !value.isNull());
result = result && (m_isRead == value.toBool());
value = query.value(OSArgumentRecordColumns::extension);
OS_ASSERT(value.isValid() && !value.isNull());
result = result && (m_extension == value.toString().toStdString());
return result;
}
示例6: qDebug
void MainWindow::on_pushButton_2_clicked()
{
if(ui->B_NIO->text().isEmpty() || ui->S_NO->text().isEmpty()){
QMessageBox::warning(this,tr("提示"),tr("不能为空"),QMessageBox::Ok);
ui->B_NIO->clear();
ui->S_NO->clear();
return;
}
QSqlQuery query;
QString s_num="";
QString b_num="";
QString o_name="";
QString o_author="";
QString o_price ="";
QString s_name="";
QString b_id="";
query.prepare("select C_NUM from COUNT where C_NO = :uid");
query.bindValue(":uid",ui->S_NO->text());
query.exec();
if(query.next()){
s_num = query.value(0).toString();
}
query.prepare("select * from BOOKS where O_ISBN = :bid");
query.bindValue(":bid",ui->B_NIO->text());
query.exec();
if(query.next()){
o_name = query.value(1).toString();
o_author = query.value(2).toString();
o_price = query.value(4).toString();
b_num = query.value(5).toString();
}
qDebug()<<s_num<<b_num;
query.prepare("SELECT S_NAME FROM STUDENTS WHERE S_NO = ?");
query.addBindValue(ui->S_NO->text());
query.exec();
if(query.next()){
s_name = query.value(0).toString();
qDebug()<<s_name;
}
if(s_num.isEmpty()){
QMessageBox::warning(this,tr("提示"),tr("输入学号错误"),QMessageBox::Ok);
ui->B_NIO->clear();
ui->S_NO->clear();
return;
}
if(b_num.isEmpty()){
QMessageBox::warning(this,tr("提示"),tr("输入ISBN错误"),QMessageBox::Ok);
ui->B_NIO->clear();
ui->S_NO->clear();
return;
}
int ss_num=s_num.toInt();
int bb_num=b_num.toInt();
++bb_num;
++ss_num;
qDebug()<<ss_num<<bb_num;
query.prepare("UPDATE BOOKS SET O_STORAGE = ? WHERE O_ISBN = ?");
query.addBindValue(QString::number(bb_num,10));
query.addBindValue(ui->B_NIO->text());
query.exec();
query.prepare("UPDATE COUNT SET C_NUM = ? WHERE C_NO = ?");
query.addBindValue(QString::number(ss_num,10));
query.addBindValue(ui->S_NO->text());
query.exec();
QDate date;
QDate oldDate;
QString oldDatetem;
date=date.currentDate();
QString newdate=date.toString("yyyy.M.d");
qDebug()<<newdate;
int countI = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(countI);
ui->tableWidget->setItem(countI,0,new QTableWidgetItem(ui->S_NO->text()));
ui->tableWidget->setItem(countI,1,new QTableWidgetItem(s_name));
ui->tableWidget->setItem(countI,2,new QTableWidgetItem(ui->B_NIO->text()));
ui->tableWidget->setItem(countI,3,new QTableWidgetItem(o_name));
ui->tableWidget->setItem(countI,4,new QTableWidgetItem(o_author));
ui->tableWidget->setItem(countI,5,new QTableWidgetItem(o_price));
ui->tableWidget->setItem(countI,6,new QTableWidgetItem(QString(tr("还回"))));
ui->tableWidget->setItem(countI,8,new QTableWidgetItem(newdate));
query.prepare("SELECT B_ID,B_TIME FROM BORROW WHERE B_NO = ? AND B_ISBN = ? AND B_ISRENT = 0");
query.addBindValue(ui->S_NO->text());
query.addBindValue(ui->B_NIO->text());
query.exec();
if(query.first()){
b_id = query.value(0).toString();
oldDatetem = query.value(1).toString();
oldDatetem.replace(QString("-"),QString(""));
qDebug()<<b_id<<oldDatetem;
}
query.prepare("UPDATE BORROW SET B_ISRENT=?,B_RENTTIME=? WHERE B_ID = ?");
query.addBindValue(1);
query.addBindValue(newdate);
query.addBindValue(b_id);
query.exec();
oldDate=oldDate.fromString(oldDatetem,"yyyyMMdd");
qDebug()<<oldDate.toString("yyyy.M.d");
int timeforBorrow = oldDate.daysTo(date);
if(timeforBorrow > 30){
qDebug()<<timeforBorrow;
//.........这里部分代码省略.........
示例7: setupLayout
//.........这里部分代码省略.........
// set up taxa tab
taxaModel = new QSqlTableModel(this);
taxaModel->setTable("taxa");
if (!tableFilter.isEmpty())
taxaModel->setFilter(tableFilter);
taxaModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
taxaModel->select();
taxaTable = new QTableView(this);
taxaTable->setModel(taxaModel);
taxaTable->resizeColumnsToContents();
taxaTable->sortByColumn(1,Qt::AscendingOrder);
taxaTable->setSortingEnabled(true);
// set up organisms tab
organismsModel = new QSqlTableModel(this);
organismsModel->setTable("organisms");
if (!tableFilter.isEmpty())
organismsModel->setFilter(tableFilter);
organismsModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
organismsModel->select();
organismsTable = new QTableView(this);
organismsTable->setModel(organismsModel);
organismsTable->resizeColumnsToContents();
organismsTable->sortByColumn(0,Qt::AscendingOrder);
organismsTable->setSortingEnabled(true);
// set up sensu tab
sensuModel = new QSqlTableModel(this);
sensuModel->setTable("sensu");
if (!tableFilter.isEmpty())
sensuModel->setFilter(tableFilter);
sensuModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
sensuModel->select();
sensuTable = new QTableView(this);
sensuTable->setModel(sensuModel);
sensuTable->resizeColumnsToContents();
sensuTable->sortByColumn(0,Qt::AscendingOrder);
sensuTable->setSortingEnabled(true);
tabWidget = new QTabWidget(this);
tabWidget->addTab(agentsTable,"Agents");
tabWidget->addTab(determinationsTable,"Determinations");
tabWidget->addTab(imagesTable,"Images");
tabWidget->addTab(taxaTable,"Names");
tabWidget->addTab(organismsTable,"Organisms");
tabWidget->addTab(sensuTable,"Sensu");
submitButton = new QPushButton(tr("&Save changes"));
submitButton->setDefault(true);
refreshButton = new QPushButton(tr("&Revert unsaved changes\nand refresh database"));
deleteButton = new QPushButton(tr("&Delete selected rows"));
quitButton = new QPushButton(tr("&Close"));
buttonBox = new QDialogButtonBox(Qt::Vertical);
buttonBox->addButton(submitButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(deleteButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(refreshButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(quitButton, QDialogButtonBox::ActionRole);
connect(submitButton, SIGNAL(clicked()), this, SLOT(submit())); // this needs to save (submit) all changes from all tables
connect(refreshButton, SIGNAL(clicked()), this, SLOT(refreshAll())); // this needs to refresh all tables to their current database values
connect(deleteButton, SIGNAL(clicked()), this, SLOT(removeSelectedRows())); // this needs to remove selected rows ONLY from current tab
connect(quitButton, SIGNAL(clicked()), this, SLOT(confirmClose()));
QHBoxLayout *mainLayout = new QHBoxLayout;
mainLayout->addWidget(tabWidget);
mainLayout->addWidget(buttonBox);
setLayout(mainLayout);
setWindowTitle("Table view");
QSqlDatabase db = QSqlDatabase::database();
db.transaction();
QSqlQuery qry;
qry.prepare("SELECT value FROM settings WHERE setting = (?)");
qry.addBindValue("view.table.location");
qry.exec();
if (qry.next())
restoreGeometry(qry.value(0).toByteArray());
bool wasMaximized = false;
qry.prepare("SELECT value FROM settings WHERE setting = (?)");
qry.addBindValue("view.table.fullscreen");
qry.exec();
if (qry.next())
wasMaximized = qry.value(0).toBool();
if (!db.commit())
{
qDebug() << "Problem committing changes to database in TableEditor::setupLayout()";
db.rollback();
}
if (wasMaximized)
this->showMaximized();
}
示例8: serv_shareNote
void MainWindow::serv_shareNote(QString noteID, QString name, QString token)
{
if (!tokens.contains(token))
{
connect(client, SIGNAL(readyRead()), this, SLOT(stop()));
QByteArray data;
data.append("TOKEN_FAIL");
send(data);
ui->textBrowser->append("Data access request. Token: "+token+" expired.");
}
else
{
QSqlQuery search;
QString id;
if (search.exec("select id from users where(nickname=\""+name+"\");"))
{
if (search.size()==0)
{
QByteArray data;
data.append("NO_SUCH_USER");
send(data);
ui->textBrowser->append("NO_SUCH_USER:"+name);
return;
}
else
{
search.next();
id = search.value(0).toString();
}
}
else
{
ui->textBrowser->append(search.lastError().text());
}
QSqlQuery check;
if (check.exec("select * from access where(user="+id+" and note="+noteID+");"))
{
if (check.size()>0)
{
ui->textBrowser->append("Already available.");
QByteArray data;
data.append("UNERR");
send(data);
return;
}
}
QSqlQuery q;
if (!q.exec("insert into access(user, note, owner) values("+id+", "+noteID+", 0);"))
{
ui->textBrowser->append(q.lastError().text());
QByteArray data;
data.append("UNERR");
send(data);
}
else
{
QByteArray data;
data.append("SHARE_NOTE_OK");
send(data);
ui->textBrowser->append("Note "+noteID+" was shared to "+id+".");
}
}
}
示例9: serv_createNote
void MainWindow::serv_createNote(QString note, QString token)
{
if (token == "")
{
QByteArray data;
data.append("UNERR");
send(data);
}
else if (!tokens.contains(token))
{
QByteArray data;
data.append("TOKEN_FAIL");
send(data);
ui->textBrowser->append("Data access request. Token: "+token+" expired.");
}
else
{
QString user = tokens[token];
QString noteID;
QJsonObject o = QJsonDocument::fromJson(note.toUtf8()).object();
QSqlQuery add;
if (add.exec("insert into notes(name,data,color) values(\""+o["theme"].toString()+"\", \""+o["text"].toString()+"\", \""+o["color"].toString()+"\");"))
{
if (add.exec("select last_insert_id();"))
{
add.next();
noteID = add.value(0).toString();
}
QJsonArray arr = o["tags"].toArray();
foreach(QJsonValue val, arr)
{
QJsonObject tag = val.toObject();
ui->textBrowser->append("searching for "+tag["name"].toString());
QString id = db_searchForTag(tag["name"].toString(),user);
QSqlQuery q;
if (!q.exec("insert into tagnote(tag, note) values("+id+", "+noteID+");"))
{
ui->textBrowser->append("insert into tagnote(tag, note) values("+id+", "+noteID+");");
ui->textBrowser->append(q.lastError().text());
}
}
arr = o["cats"].toArray();
foreach(QJsonValue val, arr)
{
QJsonObject tag = val.toObject();
QString id = db_searchForCategory(tag["name"].toString(),user);
QSqlQuery q;
if (!q.exec("insert into catnote(tag, note) values("+id+", "+noteID+");"))
{
ui->textBrowser->append("insert into catnote(tag, note) values("+id+", "+noteID+");");
ui->textBrowser->append(q.lastError().text());
}
}
QSqlQuery access;
if (!access.exec("insert into access(note, user, owner) values("+noteID+", "+user+", 1);"))
{
ui->textBrowser->append("insert into access(note, user, owner) values("+noteID+", "+user+", 1);");
ui->textBrowser->append(access.lastError().text());
}
QByteArray data;
data.append("NEW_NOTE_OK||");
data.append(db_selectUserNotes(user));
send(data);
}
示例10: supprimerClient
// ////////////////////////////////////////////////////////////////////////
//Méthode permettant de supprimer un client de la base de données
//Paramètres d'entrée :
// - Nom1 : Nom du client
// - Prenom1 : Prenom du client
//Aucun paramètre de sortie
//Valeur de retour : return true si le client a été supprimé
bool GestionBDD::supprimerClient(QString Nom1,QString Prenom1)
{
QSqlQuery query;
QMessageBox delClientMessage,trouve;
QMessageBox::StandardButtons verifSuppression;
verifSuppression=QMessageBox::question(0,"Supprimer client","Etes vous sur de vouloir supprimer le client ?",QMessageBox::Yes|QMessageBox::No);
QString Nom="";
QString Prenom="";
//Si l'utilisateur confirme la suppression alors :
if(verifSuppression==QMessageBox::Yes)
{
//Requête permettant de vérifier si le client est dans la base de données pour pouvoir être supprimé
if(query.exec("SELECT Nom,Prenom FROM asterisk.client WHERE Nom = '" + Nom1 + "' AND Prenom = '" + Prenom1 +"';"))
{
//trouve.setText("Utilisateur trouvé");
//trouve.exec();
//En cas de succès, récupération des données
while(query.next())
{
Nom =query.value(0).toString();
Prenom=query.value(1).toString();
}
//Réinitialisation des paramètres pour pouvoir faire une nouvelle éventuelle suppression
if(Nom==""&&Prenom=="")
{
trouve.setText("Utilisateur déjà supprimé");
trouve.exec();
Nom="";
Prenom="";
}else
{
//Vérification que tous les champs sont remplis
if(Nom1==""||Prenom1=="")
{
delClientMessage.setText("Veuillez remplir tout les champs");
delClientMessage.exec();
}else
{
//Requête permettant de supprimer un client selon les paramètres rentrés
if(query.exec("DELETE FROM asterisk.client WHERE Nom = '" + Nom1 + "' AND Prenom = '" + Prenom1 + "';"))
{
delClientMessage.setText("Le client a été correctement supprimé");
delClientMessage.exec();
return true;
}else
{
delClientMessage.setText("Erreur lors de la suppression du client");
delClientMessage.exec();
return false;
}
}
}
}
}else
{
delClientMessage.setText("Le client n'a pas été supprimé");
delClientMessage.exec();
return false;
}
}
示例11: ajouterClient
// /////////////////////////////////////////////////////////////////////
//Methode permettant d'ajouter un nouveau client dans la base de données
//Parametres d'entrée :
// - Nom1 : Nom du client
// - Prenom1 : Prenom du client
// - AddressIP : Adresse IP du client
// - Port : Numéro de port de l'adresse IP
// - Adresse : Adresse du client
// - oodePostal : Code postal du client
// - ville : Ville du client
// - NumeroTelApp : Numéro de téléphone (pour les appels)
// - NuméroTelSMS : Numéro de téléphone portable du client (pour les SMS)
//Aucun parametre de sortie passé dans la methode
//Valeur de retour: return true si le client a été ajouté
bool GestionBDD::ajouterClient(QString Nom1, QString Prenom1,QString AddressIP,QString Port,QString Adresse,QString codePostal,QString ville,QString NumeroTelApp,QString NumeroTelSMS)
{
QSqlQuery query;
QMessageBox clientOK,trouve;
QString Nom="";
QString Prenom="";
QString chaineVerif = "SELECT Nom,Prenom FROM asterisk.client WHERE Nom = '" + Nom1 + "' AND Prenom = '" + Prenom1 +"';";
QString chainePasseClient = "insert into client(Nom, Prenom,Adresse,CodePostal,Ville,NumeroTelApp,NumeroTelSMS)" "VALUES('" + Nom1 + "', '" + Prenom1 + "' , '" + Adresse + "' , '" + codePostal + "' , '" + ville + "' , '" + NumeroTelApp + "' , '" + NumeroTelSMS + "');";
QString chainePasseCamera = "insert into camera(AddressIP, Port)" "VALUES('" + AddressIP + "', '" + Port + "');";
//Requête de vérification de non présence d'un client déjà existant
if(query.exec(chaineVerif))
{
//trouve.setText("Utilisateur trouvé");
//trouve.exec();
//Récupération des valeurs selon la réquête demandée
while(query.next())
{
Nom =query.value(0).toString();
Prenom=query.value(1).toString();
}
//Si les valeurs récupérés sont non nulles alors le client existe déjà
if(Nom!=""&&Prenom!="")
{
trouve.setText("Utilisateur déjà existant");
trouve.exec();
//Réinitialisation des paramètres afin de pouvoir enchainer plusieurs saisies concécutives sans fermeture de la fenêtre
Nom="";
Prenom="";
}
else
{
//Requête permettant d'ajouter un client
if(query.exec(chainePasseClient))
{
//close(); fermer la fenetre apres la saisie
//return true;
//Si l'utilisateur a rempli les champs "Adresse IP" et "Numéro de port"
if(AddressIP!="" && Port!="")
{
if(query.exec(chainePasseCamera))
{
clientOK.setText("Une nouveau Client à été correctement ajouté avec une camera");
clientOK.exec();
return true;
}
}
else
{
clientOK.setText("Un nouveau Client à été correctement ajouté");
clientOK.exec();
}
}
else
{
clientOK.setText("Erreur aucun client n'as pu etre ajouté");
clientOK.exec();
return false;
}
}
}
}
示例12: documentListing
void DocDigestDetailView::documentListing( TextTemplate *tmpl, int year, int month )
{
QString minDate;
QString maxDate;
if( month > -1 ) {
QDate theDate(year, month, 1);
// not a year
minDate = theDate.toString("yyyy-MM-dd");
int lastDay = theDate.daysInMonth();
theDate.setDate(year, month, lastDay);
maxDate = theDate.toString("yyyy-MM-dd");
} else {
// is is a year
minDate = QString::number(year)+"-01-01";
maxDate = QString::number(year)+"-12-31";
}
// read data in the given timeframe from database
QSqlQuery q;
const QString query = QString("SELECT archDocID, ident, MAX(printDate) FROM archdoc WHERE "
"date BETWEEN date('%1') AND date('%2') "
"GROUP BY ident").arg(minDate, maxDate);
// qDebug() << "***" << query;
QMap<QString, QPair<int, Geld> > docMatrix;
q.prepare(query);
q.exec();
while( q.next() ) {
dbID archDocId(q.value(0).toInt());
const ArchDoc doc(archDocId);
const QString docType = doc.docType();
Geld g;
int n = 0;
if( docMatrix.contains(docType)) {
g = docMatrix[docType].second;
n = docMatrix[docType].first;
}
Geld g1 = doc.nettoSum();
g += g1;
docMatrix[docType].first = n+1;
docMatrix[docType].second = g;
}
// now create the template
tmpl->setValue("I18N_AMOUNT", i18n("Amount"));
tmpl->setValue("I18N_TYPE", i18n("Type"));
tmpl->setValue("I18N_SUM", i18n("Sum"));
QStringList doctypes = docMatrix.keys();
doctypes.sort();
foreach( const QString dtype, doctypes ) {
qDebug() << "creating doc list for "<<dtype;
tmpl->createDictionary( "DOCUMENTS" );
tmpl->setValue("DOCUMENTS", "DOCTYPE", dtype);
const QString am = QString::number(docMatrix[dtype].first);
tmpl->setValue("DOCUMENTS", "AMOUNT", am);
const QString sm = docMatrix[dtype].second.toString(DefaultProvider::self()->locale());
tmpl->setValue("DOCUMENTS", "SUM", sm);
}
示例13: writeResults
/*!
Эта реализация writeResults только для League!
*/
void League::writeResults() {
//проверяем, мб мы уже записали
QSettings stg (workdir + "/settings.ini", QSettings::IniFormat, this);
bool isbonus = QFile::exists(workdir+"/bonus.ini");
QSettings bonus (workdir +"/bonus.ini", QSettings::IniFormat, this);
qDebug() << "writing final!";
stg.beginGroup("Tournament");
bool wrote = false;
wrote = stg.value("stored", false).toBool();
qDebug() << wrote;
QSqlDatabase db = QSqlDatabase::database("players");
QSqlQuery q(db) ;
QSqlQuery sq;
QString team, nick;
sq.prepare("SELECT nick, displayname, points FROM Teams ORDER by ABS (points)");
if (!sq.exec()) {qDebug() << "write result error!" << sq.lastError().text();}
else {qDebug() << "Query done! " << sq.lastQuery();}
int rank = 0;
while (sq.next()) {
qDebug() << rank;
rank ++;
QString result;
if (rank == 1)
result.append("Чемпион, ");
else
result.append(QVariant (rank).toString() + " место, ");
result.append(sq.value(2).toString() + " очко(а, ов)");
nick = sq.value(0).toString();
team = sq.value(1).toString();
qDebug() << nick << team << result;
q.prepare("SELECT smallname FROM Players WHERE nick=:nick");
q.bindValue(":nick", nick);
if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
q.first();
QString table = q.value(0).toString();
//проверяем
q.prepare("SELECT COUNT (*) FROM "+ table + " WHERE team=:team AND trn=:trn");
if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
q.first();
if (q.value(0).toInt() == 0) {
q.prepare("INSERT INTO " + table + "(team, result) VALUES (:team, :result)");
q.bindValue(":team", team);
q.bindValue(":trn", _title);
if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
//здесь будет выдача бонусов
if (isbonus)
{
int bpoints = bonus.value(QVariant(rank).toString(), -1).toInt();
if (bpoints != -1){
q.prepare("UPDATE Rating SET bonus=(SELECT bonus FROM Rating WHERE nick=:nick)+"+QVariant(bpoints).toString()+" WHERE nick=:nick");
q.bindValue(":nick", nick);
if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();}
else {qDebug() << "Query done: " + q.executedQuery();}
syncPoints(nick);
}
}
}
}
stg.setValue("stored", true);
stg.endGroup();
stg.sync();
}
示例14: search
//.........这里部分代码省略.........
for(int i=0;i<nY;i++)
{
sign[0].points[i].V = (yiq[0][sArray[0].points[i].X][sArray[0].points[i].Y].Y > 0) ? 1 : -1;
sign[0].points[i].X = sArray[0].points[i].X;
sign[0].points[i].Y = sArray[0].points[i].Y;
}
for(int i=0;i<nI;i++)
{
sign[1].points[i].V = (yiq[0][sArray[1].points[i].X][sArray[1].points[i].Y].I > 0) ? 1 : -1;
sign[1].points[i].X = sArray[1].points[i].X;
sign[1].points[i].Y = sArray[1].points[i].Y;
}
for(int i=0;i<nQ;i++)
{
sign[2].points[i].V = (yiq[0][sArray[2].points[i].X][sArray[2].points[i].Y].Q > 0) ? 1 : -1;
sign[2].points[i].X = sArray[2].points[i].X;
sign[2].points[i].Y = sArray[2].points[i].Y;
}
qDebug()<<time.elapsed();
QSqlQuery q;
QSqlQuery qY,qI,qQ;
q.exec(QLatin1String("SELECT id,bigPath,smallPath,Y,I,Q FROM images"));
QList< QPair < int,double > > list; //list of weight
//QList< QPair < int,double > > listShot; //list of shots
//______________________________________________________________________
while(q.next())
{
int id=q.value(0).toInt();
list<< qMakePair(id, w0*(fabs(q.value(3).toInt()-yiq[0][0][0].Y)+fabs(q.value(4).toInt()-yiq[0][0][0].I)
+fabs(q.value(5).toInt()-yiq[0][0][0].Q)));
//listShot<< qMakePair(id, 0.0);
//_________________________________________________________________
}
qY.prepare(QLatin1String("SELECT x,y,sign,imageId FROM Y WHERE x=:x AND y=:y AND sign=:sign "));
for(int i=0;i<nY;i++)
{
/*qY.addBindValue(sign[0].points[i].X);
qY.addBindValue(sign[0].points[i].Y);
qY.addBindValue(sign[0].points[i].V);*/
qY.bindValue(":x",sign[0].points[i].X);
qY.bindValue(":y",sign[0].points[i].Y);
qY.bindValue(":sign",sign[0].points[i].V);
qY.exec();
//showError(qY.lastError());
while(qY.next())
{
for(int j=0;j<list.size();j++)
{
if(list.at(j).first == qY.value(3).toInt())
{
int bin=(log(sign[0].points[i].X)/log(2) > log(sign[0].points[i].Y)/log(2))? floor(log(sign[0].points[i].X)/log(2)) : floor(log(sign[0].points[i].Y)/log(2));
bin=(bin > 5) ? 5 : bin;
list[j]= qMakePair(list.at(j).first, list.at(j).second - w[0][bin]);
//listShot[j]= qMakePair(listShot.at(j).first, listShot.at(j).second + 1);
示例15: setupPatients
void MapWinCtrl::setupPatients()
{
QSqlQuery query;
QString HealthCardNum;
QString firstName ;
QString lastName;
QDateTime dateAdmitted ;
QDateTime datePlacedOnWaitingList;
int reqCare;
int occCare;
query.exec("SELECT dateAdmitted,datePlacedOnWaitingList,firstName,healthCardNum, lastName ,occCare,reqCare FROM patient ");
while (query.next()) {
HealthCardNum =query.value(3).toString();
firstName = query.value(2).toString();
lastName = query.value(4).toString();
datePlacedOnWaitingList = query.value(1).toDateTime();
dateAdmitted = query.value(0).toDateTime();
occCare = query.value(5).toInt();
reqCare = query.value(6).toInt();
Patient * aPatient = new Patient(HealthCardNum, firstName,lastName,dateAdmitted,datePlacedOnWaitingList,reqCare,occCare);
if(occCare == 0)
{
if (listOfFacility.at(0)->NUsedBedAcute())
{
listOfFacility.at(0)->addPatientAcute(aPatient);
}
}
if (occCare == 1)
{
if (listOfFacility.at(0)->NUsedBedComplex())
{
listOfFacility.at(0)->addPatientComplex(aPatient);
}
}
if (occCare == 2)
{
if (listOfFacility.at(0)->NUsedBedLTC())
{
listOfFacility.at(0)->addPatientLTC(aPatient);
}
}
// listOfPatient.append(aPatient);
}
qDebug() <<listOfFacility.at(0)->getSizePatientAcute();
qDebug() <<listOfFacility.at(0)->getSizePatientComplex();
qDebug() <<listOfFacility.at(0)->getSizePatientLTC();
query.clear();
}