示例#1
0
void SQLManager::runQuery(const QString &text, const QString &connection)
{
  kDebug() << "connection:" << connection;
  kDebug() << "text:"       << text;

  if (text.isEmpty())
    return;

  if (!isValidAndOpen(connection))
    return;

  QSqlDatabase db = QSqlDatabase::database(connection);
  QSqlQuery query(db);

  if (!query.prepare(text))
  {
    QSqlError err = query.lastError();

    if (err.type() == QSqlError::ConnectionError)
      m_model->setStatus(connection, Connection::OFFLINE);

    emit error(err.text());
    return;
  }

  if (!query.exec())
  {
    QSqlError err = query.lastError();

    if (err.type() == QSqlError::ConnectionError)
      m_model->setStatus(connection, Connection::OFFLINE);

    emit error(err.text());
    return;
  }

  QString message;

  /// TODO: improve messages
  if (query.isSelect())
  {
    if (!query.driver()->hasFeature(QSqlDriver::QuerySize))
      message = i18nc("@info/plain", "Query completed successfully");
    else
    {
      int nRowsSelected = query.size();
      message = i18ncp("@info/plain", "%1 record selected", "%1 records selected", nRowsSelected);
    }
  }
  else
  {
    int nRowsAffected = query.numRowsAffected();
    message = i18ncp("@info/plain", "%1 row affected", "%1 rows affected", nRowsAffected);
  }

  emit success(message);
  emit queryActivated(query, connection);
}
void tableTemplateWidget::deleteTemplate(void)
{
  if (templateId == 0)
    return;

  QMessageBox delTmp(QMessageBox::Question,
                     tr("Deleting template!"),
                     tr("Do you want delete template ?"),
                     QMessageBox::Yes | QMessageBox::No);

  int code = delTmp.exec();

  if (code == QMessageBox::No)
    return;

  QSqlQuery query;
  QSqlError le;

  query.prepare("DELETE FROM crossword.private_data WHERE _template = ?;");
    query.addBindValue(QVariant(templateId));
  query.exec();

  le = query.lastError();
  if (le.type() != QSqlError::NoError)
    qDebug() << "1. deleteTemplate: " << le.text();

  query.prepare("DELETE FROM crossword.grids WHERE _template = ?;");
    query.addBindValue(QVariant(templateId));
  query.exec();

  le = query.lastError();
  if (le.type() != QSqlError::NoError)
    qDebug() << "2. deleteTemplate: " << le.text();

  query.prepare("DELETE FROM crossword.templates WHERE _id = ?;");
    query.addBindValue(QVariant(templateId));
  query.exec();

  le = query.lastError();
  if (le.type() != QSqlError::NoError)
    qDebug() << "3. deleteTemplate: " << le.text();

  for (int i = 0; i < numCol; i++)
    removeColumn(0);

  setRowCount(0);

  sb->showMessage(tr("Template deleted"), 2000);

  // need for templateListWidget
  emit deletedFromDB(templateId);

  numCol = numRow = 0;
  templateId = 0;
  countWords = 0;
  wi.clear();
}
void checkDatabaseError(const QSqlDatabase &db) {
    QSqlError lastError = db.lastError();
    if (lastError.type() != QSqlError::NoError) {
#if QT_VERSION >= 0x050300
        throw Exception { lastError.nativeErrorCode().toInt(), lastError.text().toStdString() };
#else
        throw Exception { lastError.number(), lastError.text().toStdString() };
#endif
    }
}
示例#4
0
bool SqlUtils::isLockError(const QSqlError& error)
{
    if (error.type() == QSqlError::StatementError &&
        ( error.text().contains(QLatin1String("(55P03)")) || //the actual error code, not translated. needs patched QPSQL driver
          error.text().contains(QLatin1String("could not obtain lock")) )
       )
    {
        return true;
    }
    return false;
}
示例#5
0
QList<geodbObject> GeodbSql::getStreetList(QString text)
{
    QList<geodbObject> geodbObjectList;
    QString CommandText = "SELECT DISTINCT plz_code.loc_id AS id_PLZ, plz_code.text_val AS PLZ, stadt.loc_id AS id_Stadt, stadt.text_val AS Stadt, bezirk.loc_id AS id_Bezirk, bezirk.text_val AS Bezirk, ortsteil.loc_id AS id_Ortsteil, ortsteil.text_val AS Ortsteil, street.loc_id AS id_Strasse, street.text_val AS Strasse, street.valid_since AS Strasse_Von, street.valid_until AS Strasse_Bis, street.text_type AS Strasse_Typ, coord.loc_id AS id_LatLong, coord.valid_since AS LatLong_Von, coord.valid_until AS LatLong_Bis, coord.lat AS Latitude, coord.lon AS Longitude FROM geodb_textdata_berlin street, geodb_textdata_berlin plz_code_such, geodb_textdata_berlin plz_code, geodb_textdata_berlin ortsteil_such, geodb_textdata_berlin ortsteil, geodb_textdata_berlin bezirk_such, geodb_textdata_berlin bezirk, geodb_textdata_berlin stadt_such, geodb_textdata stadt, geodb_coordinates_berlin coord WHERE  ((street.text_val RLIKE :searchText) AND (street.text_type >= 101100000) AND (street.text_type <= 101400000)) AND ((plz_code_such.loc_id = street.loc_id) AND  (plz_code_such.text_type = 400100000)) AND ((plz_code.loc_id = plz_code_such.text_val) AND  (plz_code.text_type = 500300000)) AND ((ortsteil_such.loc_id = street.loc_id) AND  (ortsteil_such.text_type = 400100000)) AND ((ortsteil.loc_id = ortsteil_such.text_val) AND  (ortsteil.text_type = 101000000)) AND ((bezirk_such.loc_id = ortsteil.loc_id) AND  (bezirk_such.text_type = 400100000)) AND ((bezirk.loc_id = bezirk_such.text_val) AND  (bezirk.text_type = 100900000)) AND ((stadt_such.loc_id = bezirk.loc_id) AND  (stadt_such.text_type = 400100000)) AND ((stadt.loc_id = stadt_such.text_val) AND  (stadt.text_type = 500100000)) AND ((coord.loc_id = street.loc_id))  AND  (((street.valid_since >= '0001-01-01') AND (street.valid_until <= '3000-01-01'))  AND  ((plz_code_such.valid_since < street.valid_until) AND (plz_code_such.valid_until >= street.valid_until))  AND  ((plz_code.valid_since < street.valid_until) AND (plz_code.valid_until >= street.valid_until))  AND  ((ortsteil_such.valid_since < street.valid_until) AND (ortsteil_such.valid_until >= street.valid_until))  AND  ((ortsteil.valid_since < street.valid_until) AND (ortsteil.valid_until >= street.valid_until))  AND  ((bezirk_such.valid_since < street.valid_until) AND (bezirk_such.valid_until >= street.valid_until))  AND  ((bezirk.valid_since < street.valid_until) AND (bezirk.valid_until >= street.valid_until))  AND  ((stadt_such.valid_since < street.valid_until) AND (stadt_such.valid_until >= street.valid_until))  AND  ((stadt.valid_since < street.valid_until) AND (stadt.valid_until >= street.valid_until))  AND  ((coord.valid_since < street.valid_until) AND (coord.valid_until >= street.valid_until)))  UNION SELECT DISTINCT 0 AS id_PLZ, 'na' AS PLZ, stadt.loc_id AS id_Stadt, stadt.text_val AS Stadt, bezirk.loc_id AS id_Bezirk, bezirk.text_val AS Bezirk, ortsteil.loc_id AS id_Ortsteil, ortsteil.text_val AS Ortsteil, transport.loc_id AS id_Strasse, transport.text_val AS Strasse, transport.valid_since AS Strasse_Von, transport.valid_until AS Strasse_Bis, transport.text_type AS Strasse_Typ, coord.loc_id AS id_LatLong, coord.valid_since AS LatLong_Von, coord.valid_until AS LatLong_Bis, coord.lat AS Latitude, coord.lon AS Longitude FROM geodb_textdata_berlin_transport transport, geodb_textdata_berlin_transport ortsteil_such, geodb_textdata_berlin ortsteil, geodb_textdata_berlin bezirk_such, geodb_textdata_berlin bezirk, geodb_textdata_berlin stadt_such, geodb_textdata stadt, geodb_coordinates_berlin coord WHERE  ((transport.text_val RLIKE :searchText) AND (transport.text_type > 101100000) AND (transport.text_type <= 101400000)) AND ((ortsteil_such.loc_id = transport.loc_id) AND  (ortsteil_such.text_type = 400100000)) AND ((ortsteil.loc_id = ortsteil_such.text_val) AND  (ortsteil.text_type = 101000000)) AND ((bezirk_such.loc_id = ortsteil.loc_id) AND  (bezirk_such.text_type = 400100000)) AND ((bezirk.loc_id = bezirk_such.text_val) AND  (bezirk.text_type = 100900000)) AND ((stadt_such.loc_id = bezirk.loc_id) AND  (stadt_such.text_type = 400100000)) AND ((stadt.loc_id = stadt_such.text_val) AND  (stadt.text_type = 500100000)) AND ((coord.loc_id = transport.loc_id))  AND  (((transport.valid_since >= '0001-01-01') AND (transport.valid_until <= '3000-01-01'))  AND  ((ortsteil_such.valid_since < transport.valid_until) AND (ortsteil_such.valid_until >= transport.valid_until))  AND  ((ortsteil.valid_since < transport.valid_until) AND (ortsteil.valid_until >= transport.valid_until))  AND  ((bezirk_such.valid_since < transport.valid_until) AND (bezirk_such.valid_until >= transport.valid_until))  AND  ((bezirk.valid_since < transport.valid_until) AND (bezirk.valid_until >= transport.valid_until))  AND  ((stadt_such.valid_since < transport.valid_until) AND (stadt_such.valid_until >= transport.valid_until))  AND  ((stadt.valid_since < transport.valid_until) AND (stadt.valid_until >= transport.valid_until))  AND  ((coord.valid_since < transport.valid_until) AND (coord.valid_until >= transport.valid_until)))  UNION SELECT DISTINCT 0 AS id_PLZ, 'na' AS PLZ, land.loc_id AS id_Stadt, land.text_val AS Stadt, kreis.loc_id AS id_Bezirk, kreis.text_val AS Bezirk, name.loc_id AS id_Ortsteil, name.text_val AS Ortsteil, transport2.loc_id AS id_Strasse, transport2.text_val AS Strasse, transport2.valid_since AS Strasse_Von, transport2.valid_until AS Strasse_Bis, transport2.text_type AS Strasse_Typ, coord.loc_id AS id_LatLong, coord.valid_since AS LatLong_Von, coord.valid_until AS LatLong_Bis, coord.lat AS Latitude, coord.lon AS Longitude FROM geodb_textdata_berlin_transport transport2, geodb_textdata_berlin_transport name_such, geodb_textdata name, geodb_textdata kreis, geodb_textdata kreis_such, geodb_textdata land_such, geodb_textdata land, geodb_coordinates_berlin coord WHERE  ((transport2.text_val RLIKE :searchText) AND (transport2.text_type > 101100000) AND (transport2.text_type <= 101400000)) AND ((name_such.loc_id = transport2.loc_id) AND  (name_such.text_type = 400100000)) AND ((name.loc_id = name_such.text_val) AND  (name.text_type = 500100000)) AND ((kreis_such.loc_id = name.loc_id) AND  (kreis_such.text_type = 400100000)) AND ((kreis.loc_id = kreis_such.text_val) AND  (kreis.text_type = 500100000)) AND ((land_such.loc_id = kreis.loc_id) AND  (land_such.text_type = 400100000)) AND ((land.loc_id = land_such.text_val) AND  (land.text_type = 500100000)) AND ((coord.loc_id = transport2.loc_id))  ORDER BY Stadt, Strasse, PLZ, Bezirk, Ortsteil";
    QSqlQuery query = QSqlQuery(db);
    if(!query.prepare(CommandText))
    {
        QSqlError err = query.lastError();
        qDebug() << err.text() + "\n";
        qDebug() << CommandText + " line:" + QString("%1").arg(__LINE__) +"\n";
    }
    //query.bindValue(":searchText", "'"+text+"'");
    CommandText.replace(":searchText", "'"+text+"'");
    //qDebug()<<CommandText;
    bool bQuery = query.exec(CommandText);
    if(!bQuery)
    {
        QSqlError err = query.lastError();
        qDebug() << err.text() + "\n";
        qDebug() << CommandText + " line:" + QString("%1").arg(__LINE__) +"\n";
        db.close();
        exit(EXIT_FAILURE);
    }
    while(query.next())
    {
        geodbObject go;
        go.id_PLZ = query.value(0).toInt();
        go.PLZ = query.value(1).toString();
        go.idStadt = query.value(2).toInt();
        go.Stadt = query.value(3).toString();
        go.idBezirk = query.value(4).toInt();
        go.Bezirk = query.value(5).toString();
        go.idOrsteil=query.value(6).toInt();
        go.Ortstiel = query.value(7).toString();
        go.idStrasse = query.value(8).toInt();
        go.Strasse = query.value(9).toString();
        go.Strasse_von = query.value(10).toString();
        go.Strasse_bis = query.value(11).toString();
        go.Strasse_type = query.value(12).toInt();
        go.idLatLong = query.value(13).toInt();
        go.LatLong_von = query.value(14).toString();
        go.LatLon_bis = query.value(15).toString();
        go.latitude = query.value(16).toDouble();
        go.longitude = query.value(17).toDouble();
        geodbObjectList.append(go);
    }
    return geodbObjectList;
}
示例#6
0
void firstDiagnostics::on_buttonBox_accepted()
{

    QSqlDatabase::database().transaction();
    QSqlQuery query;
    query.prepare("insert into diagnosis(fk_customer, fk_doctor, type, fk_partner, dateD, timeD) values(?, ?, ?, ?, ?, ?)");
    query.addBindValue(customerID);
    query.addBindValue(ui->doctorCombobox->itemData(ui->doctorCombobox->currentIndex()));
    query.addBindValue(0);
    query.addBindValue(partnerID);
    query.addBindValue(ui->dateEdit->date());
    query.addBindValue(ui->timeEdit->time());
    query.exec();
    query.clear();
    query.prepare("select fk_customerCard from Customer where id = ?");
    query.addBindValue(customerID);
    query.exec();
    int cardID = 0;
    if(query.next())
        cardID = query.value(0).toInt();
    query.clear();
    query.prepare("insert into custCardDoctor values(?, ?)");
    query.addBindValue(cardID);
    query.addBindValue(ui->doctorCombobox->itemData(ui->doctorCombobox->currentIndex()));
    query.exec();
    if(!QSqlDatabase::database().commit())
    {
        QSqlError err;
        err = QSqlDatabase::database().lastError();
        QSqlDatabase::database().rollback();
        QMessageBox::warning(this, tr("Error"), err.text());

    }
    this->deleteLater();
}
示例#7
0
bool DDbConfig::apply()
{
    bool isSql = false;
    {
        QSqlDatabase db = QSqlDatabase::addDatabase( cbDriver->currentText(), "test" );
        db.setHostName( edtDbHost->text() );
        db.setDatabaseName( edtDbName->text() );
        db.setUserName( edtDbUser->text() );
        db.setPassword( edtDbPassword->text() );
        db.setPort( sbDbPort->value() );
        db.setConnectOptions( edtDbOptions->toPlainText() );

        isSql = db.open();

        if (!isSql) { // Error
            QSqlError err = db.lastError();
            QMessageBox::warning( this, tr("Not connected"),
                                  tr("Can't create connection to SQL server.\nError text: %1")
                                  .arg(err.text()) );
        } else {
            db.close();
            QMessageBox::information( this, tr("Connection sucsessfull"),
                                      tr("Connection to data base succsessfully created.") );
        }
    }
    QSqlDatabase::removeDatabase( "test" );

    return isSql;
}
void ConnDlg::on_okButton_clicked()
{
    if (ui.comboDriver->currentText().isEmpty())
    {
        ui.status_label->setText(tr("请选择一个数据库驱动!"));
        ui.comboDriver->setFocus();
    }
    else if(ui.comboDriver->currentText() =="QSQLITE")
    {
        addSqliteConnection();
        //创建数据库表,如已存在则无须执行
        creatDB();
        accept();
    }
    else
    {
        QSqlError err = addConnection(driverName(), databaseName(), hostName(),userName(), password(), port());
        if (err.type() != QSqlError::NoError)
            ui.status_label->setText(err.text());
        else
            ui.status_label->setText(tr("连接数据库成功!"));
        //创建数据库表,如已存在则无须执行
        accept();
        }
}
示例#9
0
void partner::on_buttonBox_accepted()
{
	QSqlQuery query;
	if(mode == insertMode)
	{

		query.prepare("insert into Partner(Name, Surname, Patronimic, pasport_data, phone) values(?,?,?,?,?)");
		query.addBindValue(ui->nameEdit->text());
		query.addBindValue(ui->surnameEdit->text());
		query.addBindValue(ui->patronimicEdit->text());
		query.addBindValue(ui->passportEdit->text());
		query.addBindValue(ui->phoneEdit->text());
	}
	else if(mode == updateMode)
	{
		query.prepare("update Partner set Name=?, Surname=?, Patronimic=?, pasport_data=?, phone=? where id=?");
		query.addBindValue(ui->nameEdit->text());
		query.addBindValue(ui->surnameEdit->text());
		query.addBindValue(ui->patronimicEdit->text());
		query.addBindValue(ui->passportEdit->text());
		query.addBindValue(ui->phoneEdit->text());
		query.addBindValue(id);
	}
	if (!query.exec())
	{
		QSqlError err;
		err = query.lastError();
		QMessageBox::warning(this, tr("Error"), err.text());
	}

	this->deleteLater();
}
示例#10
0
文件: sql.cpp 项目: sakazuki/actiona
	QScriptValue Sql::execute(const QString &queryString)
	{
        bool result = false;

        if(queryString.isEmpty())
		{
            result = mQuery.exec();
		}
        else
        {
            mQuery = QSqlQuery(*mDatabase);
            mQuery.setForwardOnly(true);

            result = mQuery.exec(queryString);
        }

        if(!result)
		{
			QSqlError error = mQuery.lastError();
			throwError("ExecuteQueryError", tr("Failed to execute the query : %1").arg(error.text()));
			return thisObject();
		}

		return thisObject();
	}
示例#11
0
文件: kraftdb.cpp 项目: KDE/kraft
int KraftDB::processSqlCommands( const SqlCommandList& commands )
{
    int cnt = 0;

    foreach( SqlCommand cmd, commands ) {
        if( !cmd.message().isEmpty() ) {
            emit statusMessage( cmd.message() );
        }

        if( !cmd.command().isEmpty() ) {
            bool res = true;
            QSqlQuery q;
            q.clear();
            res = q.exec(cmd.command()) || cmd.mayfail();

            if ( res ) {
                kDebug() << "Successful SQL Command: " << cmd.command() << endl;
                cnt ++;
            } else {
                QSqlError err = q.lastError();
                res = false;
                kDebug() << "###### Failed SQL Command " << cmd.command() << ": " << err.text() << endl;
            }
            q.clear();
            emit processedSqlCommand( res );

        }
    }
    return cnt;
}
示例#12
0
void XModel::submitAll(){
	bool b = QSqlRelationalTableModel::submitAll();
    if(b == false){
    	QSqlError err = lastError();
    	yERROR(err.text());
    }
}
示例#13
0
bool SvDeviceEditor::loadKTSs()
{
  QSqlQuery* q = new QSqlQuery(SQLITE->db);
  QSqlError serr = SQLITE->execSQL(QString(SQL_SELECT_KTSS_LIST), q); 
  if(QSqlError::NoError != serr.type()) {
    
    _last_error = serr.text();
    delete q;
    return false;
  }

  while(q->next())
    ui->cbDeviceType->addItem(q->value("kts_name").toString(), q->value("kts_id").toUInt());
  
  q->finish();
  delete q;
  
  if(ui->cbDeviceType->count()) ui->cbDeviceType->setCurrentIndex(0);
  ui->bnSave->setEnabled(!ui->cbDeviceType->currentData().isNull());
  
  connect(ui->cbDeviceType, SIGNAL(currentIndexChanged(int)), this, SLOT(updateKTSInfo(int)));
  
  return true;
  
}
示例#14
0
int PushDAO::add(const Push &push)
{
    int insertId = -1;
    QSqlQuery sqlQuery(SQLConnection());

    const QString query("INSERT INTO push (seqnum, pushdate, type, pushtime, extension, content, unread)"
                        "VALUES(:seqnum, :pushdate, :type, :pushtime, :extension, :content, :unread)");

    sqlQuery.prepare(query);

    sqlQuery.bindValue(":pushdate", push.pushDateAsString());
    sqlQuery.bindValue(":type", push.contentType());
    sqlQuery.bindValue(":pushtime", push.pushTime());
    sqlQuery.bindValue(":extension", push.fileExtension());
    sqlQuery.bindValue(":content", push.content().toBase64(), QSql::In | QSql::Binary);
    sqlQuery.bindValue(":unread", push.unread());
    sqlQuery.exec();

    const QSqlError err = sqlQuery.lastError();

    if (err.isValid()) {
        qWarning() << "Error executing SQL statement: " << query << ". ERROR: " << err.text();
    } else {
        if (sqlQuery.lastInsertId().isValid()) {
            insertId = sqlQuery.lastInsertId().toInt();
        }
    }

    return insertId;
}
示例#15
0
void dataeditfrm::newentry()
{
    //prepare supplier entry
    int i, ii;
    QString supl = "";
    for(i=0;i<tabsuppliers->rowCount();i++)
    {
    	for(ii=0; ii<tabsuppliers->columnCount(); ii++)
    	{
    		QTableWidgetItem *item = new QTableWidgetItem;
    		item = tabsuppliers->item(i, ii);
    		if(item != 0)
    			supl += tabsuppliers->item(i, ii)->text() + ":#:";
			supl = supl.leftJustified(supl.length()-1, '.', true) + "#:";
   		}
   	}
    
    QString state = "0";
    if(chkactive->isChecked())
		state = "1";
    QString connstr = QString("INSERT INTO `"+lbldatatab->text()+"` (`ID`, `col1`, `col2`, `col3`, `col4`, `col5`, `col6`, `col7`, `col8`, `col9`, `col10`, `col11`, `col12`, `col13`, `col14`, `col15`, `col16`, `col17`, `col18`, `col19`, `col20`, `col21`) VALUES (NULL, '%1', '%2', '%3', '%4', '%5', '%6', '%7', '%8', '%9'").arg(txtlabel->text()).arg(txtdescription->toPlainText()).arg(txtstock->text()).arg(txtminquantity->text()).arg(txtunit->text()).arg(txtorderquantity->text()).arg(txtpurchaseprice->text()).arg(txtsellprice->text()).arg(supl);
    connstr += QString(", '%1', '%2', '%3', '%4', '%5', '%6'").arg(txtpackage->text()).arg(txtweight->text()).arg(cmbvat->currentIndex()).arg(state).arg(txtwebname->text()).arg(txtwebimage->text());
    connstr += QString(", '%1', '%2', '%3', '%4', '%5', '%6');").arg(txtweburl->text()).arg(QDate::currentDate().toString("yyyy-MM-dd")).arg(QDate::currentDate().toString("yyyy-MM-dd")).arg(txtsalesdate->date().toString("yyyy-MM-dd")).arg(txtcomments->toPlainText()).arg(txtstockpos->text());
    QSqlQuery query(connstr);
    
    QSqlError qerror = query.lastError();
	if(qerror.isValid())
		QMessageBox::information ( 0, tr ( "Error during update..." ), qerror.text() );
}
示例#16
0
void DbFunc::openDatabaseOrDie(QSqlDatabase& db, const QString& filename)
{
    // Opens a database.
    QString dir = QStandardPaths::standardLocations(
        QStandardPaths::AppDataLocation).first();
    // Under Linux: ~/.local/share/camcops/
    if (!QDir(dir).exists()) {
        if (QDir().mkdir(dir)) {
            qDebug() << "Made directory:" << dir;
        } else {
            UiFunc::stopApp("DbFunc::openDatabaseOrDie: Failed to make "
                            "directory: " + dir);
        }
    }
    // http://stackoverflow.com/questions/3541529/is-there-qpathcombine-in-qt4
    QString fullpath = QDir::cleanPath(dir + "/" + filename);
    db.setDatabaseName(fullpath);
    if (db.open()) {
        qInfo() << "Opened database:" << fullpath;
    } else {
        QSqlError error = db.lastError();
        qCritical() << "Last database error:" << error;
        qCritical() << "Database:" << db;
        QString errmsg = QString(
            "DbFunc::openDatabaseOrDie: Error: connection to database failed. "
            "Database = %1; error number = %2; error text = %3"
        ).arg(fullpath, QString::number(error.number()), error.text());
        UiFunc::stopApp(errmsg);
    }
}
示例#17
0
void MainWindow::addTask(QString difficulty, QString comment, QString answer, QString source) {
    // *********************
    QFile f(source);
    if (f.open(QIODevice::ReadOnly)) {
        ba = f.readAll();
        f.close();
    }
    else {
        debug("Cannot load an image");
        return;
    }
    // ********************* loading a task

    execution = "INSERT INTO tasks VALUES (DEFAULT, :IMAGE, " + answer + ", '" + comment + "', " + difficulty + ", ";
    for (int i = 0; i < tasksInfo.size(); i++) {
        execution += tasksInfo[i] == false ? "0, " : "1, ";
    }
    execution.resize(execution.size() - 2);
    execution += ");";
  //  debug(execution);
    query->prepare(execution.toUtf8()); //
    query->bindValue(":IMAGE", ba);
    if (!query->exec()) {
        QSqlError err;
        err = query->lastError();
        debug(err.text());
    }
    else {
        debug("Works fine");
    }
}
示例#18
0
void checkMySQLError(QSqlQuery& q) {
    QSqlError e = q.lastError();
    if(!e.isValid())
        return;//no error
    qDebug()<<"got MySQL-Error"<<e.number()<<e.text()<<"/"<<e.databaseText()<<"/"<<e.driverText();
    qDebug()<<"on query"<<q.lastQuery();
    qDebug()<<"Terminating Application";
    QCoreApplication::quit();
}
示例#19
0
void UniPAX::mysql::MySQLManager::exec(QSqlQuery& query, QString error)
{
	query.exec();
	QSqlError e = query.lastError();
	if (e.isValid())
	{
		throw std::runtime_error(error.toStdString() + ": " + e.text().toStdString() + " -- " + query.lastQuery().toStdString());
	}
}
示例#20
0
QString Query::lastErrorText() const
{
	QString ret;
	QSqlError err = lastError();
	if(err.isValid()) {
		ret = err.text();
	}
	return ret;
}
示例#21
0
//Return Values
//True:     Error Occurred
//False:    No Error Occurred / Detected
//------------------------------------------------------------------------
bool DRCDB::ExtractError(const QSqlError &error_object)
{
    DB_ERROR = error_object.isValid();

    if (DB_ERROR)
        LastErrors.push_back(error_object.text());

    return DB_ERROR;
}
void templateeditfrm::inserttemplate()
{
	QString qstr = QString("INSERT INTO `templates` ( `ID` , `name` , `description` , `data` , `created_by` , `created` ) VALUES ('', '%1', '%2', '%3', '%4', '%5');").arg(txtname->text()).arg(txtdescription->toPlainText()).arg(txtdata->toPlainText().replace("\\", "\\\\")).arg(username).arg(QDate::currentDate().toString("yyyy-MM-dd"));
	QSqlQuery query(qstr);
	QSqlError qerror = query.lastError();
	if(qerror.isValid())
		QMessageBox::warning ( 0, tr ( "Template not saved..." ), qerror.text());
	QMessageBox::information( 0, tr ( "Template saved..." ), tr ( "Template successfully saved in the database." ) );
	this->close();
}
void templateeditfrm::updatetemplate()
{
	QString qstr = QString("UPDATE templates SET `name` = '%1', `description`='%2', `data`='%3' , `modificated_by`='%4', `modificated`='%5' WHERE `ID`='%6';").arg(txtname->text()).arg(txtdescription->toPlainText()).arg(txtdata->toPlainText().replace("\\", "\\\\")).arg(username).arg(QDate::currentDate().toString("yyyy-MM-dd")).arg(templateid);
	QSqlQuery query(qstr);
	QSqlError qerror = query.lastError();
	if(qerror.isValid())
		QMessageBox::warning ( 0, tr ( "Template not saved..." ), qerror.text());
	QMessageBox::information( 0, tr ( "Template saved..." ), tr ( "Template successfully saved in the database." ) );
	templateid = "";
	this->close();
}
示例#24
0
QSqlQuery UniPAX::mysql::MySQLManager::exec(QString sql, QString error)
{
	QSqlQuery q = qdatabase.exec(sql);
	QSqlError e = q.lastError();
	if (e.isValid())
	{
		throw std::runtime_error(error.toStdString() + ": " + e.text().toStdString() + " -- " + sql.toStdString());
	}

	return q;
}
示例#25
0
void AsyncSqlWorker::removeFeedFromDB(const QVariant& requestList,
		bb::data::DataAccessReply* replyData) {
	LOG_DEBUG(TAG_ASYNCWORKER, "removeFeedFromDB");
	QVariantMap resultMap;
	resultMap.insert("result", requestList);
	replyData->setResult(resultMap);

	QVariantMap map = requestList.toMap();
	QSqlQuery sqlQuery(m_pSqlDatabase);
	sqlQuery.prepare("DELETE FROM FEED_TABLE WHERE feedUrl = :feedUrl");
	sqlQuery.bindValue(":feedUrl", map.value("feedUrl").toString());
	sqlQuery.exec();
	QSqlError err = sqlQuery.lastError();
	if (err.isValid()) {
		qWarning() << "AsyncSqlWorker::removeFeedFromDB SQL reported an error : "
				<< err.text();
		replyData->setError(DataAccessErrorType::OperationFailure, err.text());
		return;
	}
}
示例#26
0
bool DataManager::connect() {
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    db.setDatabaseName("DBCore");
    db.setUserName("djon");
    db.setPassword("dj0n2011");
    bool ok = db.open();
    if (!ok) {
        QSqlError error = db.lastError();
        qDebug(error.text().toStdString().c_str());
    }
    return ok;
}
示例#27
0
QList<Db_dat> load_operation_with_filter(const QString& str, bool& bRet, double *d_income, double *d_outgoes)
{
	QList<Db_dat> lRet;
	Db_dat data;
	bRet = false;
	
	double i_income = 0.00;
	double i_outgoes = 0.00;
	
	QSqlQuery query(QSqlDatabase::database(data_u.NameDB));
	
	QString querystring = "select * from operation where "+str;
	
    if (!query.exec(querystring))
    {
		QSqlError er = query.lastError();//"Failed to execute filter: select * from operation where date_s like";
		data.descr = er.text();
		return lRet;
	}
	
    while (query.next())
    {
		data.date = query.value(0).toString();
		
		data.type = query.value(1).toString();//get type operation
		
        double icount = query.value(2).toDouble(); //get count cash operation
		if(data.type == "income")
        {
            i_income += icount;
        }
        else if(data.type == "outgoes")
        {
            i_outgoes += icount;
        }
        data.count_d = icount;
		
		data.currency = query.value(3).toString();
		data.descr = query.value(4).toString();//get description operation
                   		   
		bRet=true;
		lRet.append(data);
	}
	
    if(d_income && d_outgoes)
    {
	   *d_income = i_income;
	   *d_outgoes = i_outgoes;
	}
	
	return lRet;
}
void Tf::writeQueryLog(const QString &query, bool success, const QSqlError &error)
{
    QString q = query;

    if (!success) {
        QString err = (!error.databaseText().isEmpty()) ? error.databaseText() : error.text().trimmed();
        if (!err.isEmpty()) {
            err = QLatin1Char('[') + err + QLatin1String("] ");
        }
        q = QLatin1String("(Query failed) ") + err + query;
    }
    Tf::traceQueryLog("%s", qPrintable(q));
}
示例#29
0
QVariantMap ScriptQuery::lastError()
{
  QVariantMap m;
  QSqlError err = _query.lastError();
  m.insert("databaseText", err.databaseText());
  m.insert("driverText", err.driverText());
  m.insert("text", err.text());
  m.insert("number", err.number());
  m.insert("type", err.type());
  m.insert("isValid", QVariant(err.isValid(), 0));

  return m;
}
示例#30
0
void XModel::editRecFldById(QString id, int fldIdx, QVariant value){
	setFilter(QString("%1.id = '%2'").arg(m_tbl).arg(id));
	if (rowCount() == 1) {
	    bool b = setData(index(0, fldIdx), value);
	    if(b == false){
	    	QSqlError err = lastError();
	    	yERROR(err.text());
	    }
	    submit();
	} else {
		yERROR(QString("Can't find %1 to edit.").arg(id));
	}
}