当前位置: 首页>>代码示例>>C++>>正文


C++ QSqlQuery::lastError方法代码示例

本文整理汇总了C++中QSqlQuery::lastError方法的典型用法代码示例。如果您正苦于以下问题:C++ QSqlQuery::lastError方法的具体用法?C++ QSqlQuery::lastError怎么用?C++ QSqlQuery::lastError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QSqlQuery的用法示例。


在下文中一共展示了QSqlQuery::lastError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: sImport

void ImportWindow::sImport()
{
  _log->append(tr("Import Started..."));
  Q3ListBoxItem * item = _reports->firstItem();
  Q3ListBoxItem * next = 0;
  while(item)
  {
    next = item->next();
    if(item->isSelected())
    {
      QString xml_file = ((ListBoxReportItem*)item)->report();

      QString report_name  = QString::null;
      QString report_desc  = QString::null;
      QString report_src   = QString::null;
      int     report_grade = ((ListBoxReportItem*)item)->grade();

      if(!xml_file.isEmpty())
      {
        QFile file(xml_file);
        if(file.open(QIODevice::ReadOnly))
        {
          QDomDocument doc;
          QString errMsg;
          int errLine, errCol;
          if(doc.setContent(&file, &errMsg, &errLine, &errCol))
          {
            QDomElement root = doc.documentElement();
            if(root.tagName() == "report")
            {
              for(QDomNode n = root.firstChild();
                    !n.isNull(); n = n.nextSibling())
              {
                if(n.nodeName() == "name")
                  report_name = n.firstChild().nodeValue();
                else if(n.nodeName() == "description")
                  report_desc = n.firstChild().nodeValue();
              }
              report_src = doc.toString();

              if(!report_name.isEmpty())
              {
                QSqlQuery qry;
                QSqlQuery query;

                qry.prepare("SELECT report_id "
                            "  FROM report "
                            " WHERE ((report_name=:rptname) "
                            "   AND (report_grade=:rptgrade));");
                qry.bindValue(":rptname",  report_name);
                qry.bindValue(":rptgrade", report_grade);
                qry.exec();
                if(qry.first())
                {
                  // update
                  query.prepare("UPDATE report "
                                "   SET report_descrip=:rptdescr, "
                                "       report_source=:rptsrc "
                                " where report_id=:rptid "
                                "   and report_name=:rptname;");
                  query.bindValue(":rptdescr", report_desc);
                  query.bindValue(":rptsrc",   report_src);
                  query.bindValue(":rptid", qry.value(0));
                  query.bindValue(":rptname",  report_name);
                }
                else
                {
                  // insert
                  query.prepare("INSERT INTO report "
                                "       (report_name, report_descrip, report_source, report_grade) "
                                "VALUES (:rptname, :rptdescr, :rptsrc, :rptgrade);");
                  query.bindValue(":rptname",  report_name);
                  query.bindValue(":rptdescr", report_desc);
                  query.bindValue(":rptsrc",   report_src);
                  query.bindValue(":rptgrade", report_grade);
                }
                
                if(!query.exec())
                {
                  QSqlError err = query.lastError();
                  _log->append(tr("<font color=red>The following error was encountered while trying to import %1 into the database:\n"
                                  "\t%2\n\t%3\n</font>")
                                .arg(xml_file)
                                .arg(err.driverText())
                                .arg(err.databaseText()));
                }
                else
                  _log->append(tr("Import successful of %1").arg(xml_file));
              }
              else
                _log->append(tr("<font color=orange>The document %1 does not have a report name defined\n</font>")
                              .arg(xml_file));
            }
            else
              _log->append(tr("<font color=red>XML Document %1 does not have root node of report\n</font>")
                            .arg(xml_file));
          }
          else
            _log->append(tr("<font color=red>Error parsing file %1: %2 on line %3 column %4\n</font>")
                          .arg(xml_file).arg(errMsg).arg(errLine).arg(errCol));
//.........这里部分代码省略.........
开发者ID:Wushaowei001,项目名称:xtuple,代码行数:101,代码来源:importwindow.cpp

示例2: _AddDataArrayBar

int CSqliteDbOper::_AddDataArrayBar(unsigned int nTableKey, LstInstrumentBarInfoT*  pListBar)
{
	BOOST_LOG_FUNCTION();
	int nFunRes = 0;
	bool bExecRes = false;
	std::string strSQL;
	std::string strTimeStr;
	LstInstrumentBarInfoIterT iterLst;
	CInstrumentBarInfo* pInstrumentBarInfo = NULL;
	//QVariantList lstInstrumentID;
	QVariantList lstTimestamp;
	QVariantList lstOpen;
	QVariantList lstClose;
	QVariantList lstHigh;
	QVariantList lstLow;
	QVariantList lstVolume;
	QSqlQuery* pQSqlQueryForInseert = NULL;

	if (pListBar->empty())
	{
		nFunRes = 0;
		return nFunRes;
	}

	pQSqlQueryForInseert = new QSqlQuery(*m_pQSqlDataBaseBAR);

	strSQL = _BuildSQLForInsertBarData(nTableKey);

	LOG_DEBUG<<"m_pDBOperParam->m_nInstrumentID="<<m_pDBOperParam->m_nInstrumentID
		<<"  "<<"strSQL="<<strSQL
		<<"  "<<"pLstInstrumentBarInfo.size="<<pListBar->size();

	pQSqlQueryForInseert->prepare(strSQL.c_str());

	iterLst = pListBar->begin();
	while (iterLst != pListBar->end())
	{
		pInstrumentBarInfo = (*iterLst);

		//lstInstrumentID<<m_pDBOperParam->m_nInstrumentID;
		strTimeStr = m_pUtilityFun->dataTimeToStr(pInstrumentBarInfo->m_BarInfo.Time);
		lstTimestamp << strTimeStr.c_str();
		lstOpen<<pInstrumentBarInfo->m_BarInfo.Open;
		lstClose<<pInstrumentBarInfo->m_BarInfo.Close;
		lstHigh<<pInstrumentBarInfo->m_BarInfo.High;
		lstLow<<pInstrumentBarInfo->m_BarInfo.Low;
		lstVolume<<pInstrumentBarInfo->m_BarInfo.Volume;

		iterLst++;
	}//while

	//pQSqlQueryForInseert->addBindValue(lstInstrumentID);
	pQSqlQueryForInseert->addBindValue(lstTimestamp);
	pQSqlQueryForInseert->addBindValue(lstOpen);
	pQSqlQueryForInseert->addBindValue(lstClose);
	pQSqlQueryForInseert->addBindValue(lstHigh);
	pQSqlQueryForInseert->addBindValue(lstLow);
	pQSqlQueryForInseert->addBindValue(lstVolume);

	bExecRes = pQSqlQueryForInseert->execBatch();
	if (!bExecRes)
	{
		nFunRes = -1;
		LOG_ERROR<<"execBatch strSQL="<<strSQL<<" pLstInstrumentBarInfo.size="<<pListBar->size()
			<<" "<<"error:"<<pQSqlQueryForInseert->lastError().text().toStdString();
	}

	if (NULL != pQSqlQueryForInseert)
	{
		delete pQSqlQueryForInseert;
		pQSqlQueryForInseert = NULL;
	}
	return nFunRes;
}
开发者ID:shenglonglinapple,项目名称:slin_code,代码行数:74,代码来源:SqliteDbOper.cpp

示例3: addRecordOfTablePost

void SizPostForm::addRecordOfTablePost()
{
    QTextStream stream(&exchangeFile);
    QString line;
    while(!stream.atEnd()){
        stream.readLine();
    }
    if(checkingFill()){
        ViewListTable listTable("","post",this);
        listTable.exec();
        QString postId = listTable.returnValue();

        QSqlQuery query;
        query.prepare("SELECT * FROM post WHERE postid = :id");
        query.bindValue(":id",postId);
        query.exec();
        while(query.next()){
            int rowCount = postView->rowCount();
            bool insert = true;
            //Проверка на существование записи
            if (rowCount != 0){
                for(int kk = 0; kk < rowCount; ++kk){
                    QString yy = postView->item(kk,2)->text();
                    QString pp = query.value(1).toString();
                    if(yy == pp){
                        QString tempString = query.value(1).toString();
                        tempString += QObject::trUtf8(" is availble!");
                        QMessageBox::warning(this,QObject::trUtf8("Atention!!!"),tempString);
                        insert = false;
                        break;
                    }
                }
            }
            if(insert){
                addIntoTable = true;
                postView->insertRow(rowCount);

                NumPrefix numPrefix;
                QString idPostSizList = numPrefix.getPrefix("postsizlist");

                QTableWidgetItem *itemID = new QTableWidgetItem;
                postView->setItem(rowCount,0,itemID);
                postView->item(rowCount,0)->setText(idPostSizList);

                QTableWidgetItem *itemPostSiz = new QTableWidgetItem;
                postView->setItem(rowCount,1,itemPostSiz);
                postView->item(rowCount,1)->setText(indexTemp);

                QTableWidgetItem *itemPost = new QTableWidgetItem;
                postView->setItem(rowCount,2,itemPost);
                postView->item(rowCount,2)->setText(query.value(1).toString());

                QSqlQuery queryPSL;
                queryPSL.prepare("INSERT INTO postsizlist ("
                                 "postsizlistid, postsizid, postid"
                                 ") VALUES(:postsizlistid, :postsizid, :postid)");
                queryPSL.bindValue(":postsizlistid",idPostSizList);
                queryPSL.bindValue(":postsizid",indexTemp);
                queryPSL.bindValue(":postid",query.value(0).toString());
                queryPSL.exec();
                if(!queryPSL.isActive()){
                    QMessageBox::warning(this,QObject::trUtf8("Post SIZ List Table, INSERT ERROR!"),queryPSL.lastError().text());
                    return;
                }
                line += "INSERT INTO postsizlist (postsizlistid, postsizid, postid) VALUES('";
                line += idPostSizList.toUtf8();
                line += "', '";
                line += indexTemp.toUtf8();
                line += "', '";
                line += query.value(0).toString().toUtf8();
                line += "')";
                line += "\r\n";
                stream<<line;
            }
        }
    }
}
开发者ID:AndrewBatrakov,项目名称:EmployeeClient,代码行数:77,代码来源:sizpostform.cpp

示例4: main

int main(int argc, char *argv[])
{
  QCoreApplication application(argc, argv);
  application.addLibraryPath(".");

  QTextStream out(stdout, QIODevice::WriteOnly);

  if (application.argc() > 1)
  {
    QString databaseURL;
    QString username;
    QString passwd;
    QString arguments;

    QString xml_file = QString::null;
    int     report_grade = 0;

    for (int counter = 1; counter < application.argc(); counter++)
    {
      QString arguments(application.argv()[counter]);

      if (arguments.startsWith("-databaseURL=", Qt::CaseInsensitive))
        databaseURL = arguments.right(arguments.length() - 13);
      else if (arguments.startsWith("-username=", Qt::CaseInsensitive))
        username = arguments.right(arguments.length() - 10);
      else if (arguments.startsWith("-passwd=", Qt::CaseInsensitive))
        passwd = arguments.right(arguments.length() - 8);
      else if (arguments.startsWith("-f=", Qt::CaseInsensitive))
        xml_file = arguments.right(arguments.length() - 3);
      else if (arguments.startsWith("-grade=", Qt::CaseInsensitive))
        report_grade = (arguments.right(arguments.length() - 7)).toInt();
      else if(!arguments.startsWith("-"))
        xml_file = arguments;
    }

    QString report_name = QString::null;
    QString report_desc = QString::null;
    QString report_src  = QString::null;

    if(xml_file != "") {
        QFile file(xml_file);
        if(file.open( QIODevice::ReadOnly )) {
            QDomDocument doc;
            QString errMsg;
            int errLine, errCol;
            if(doc.setContent(&file, &errMsg, &errLine, &errCol)) {
                QDomElement root = doc.documentElement();
                if(root.tagName() == "report") {
                    for(QDomNode n = root.firstChild();
                            !n.isNull(); n = n.nextSibling() ) {
                        if(n.nodeName() == "name") {
                            report_name = n.firstChild().nodeValue();
                        } else if(n.nodeName() == "description") {
                            report_desc = n.firstChild().nodeValue();
                        }
                    }
                    report_src  = doc.toString();

                    if(report_name == "") {
                        out << "The document " << xml_file << " does not have a report name defined." << endl;
                    }
                } else {
                    out << "XML Document " << xml_file << " does not have root node of report." << endl;
                }
            } else {
                out << "Error parsing file " << xml_file << ": " << errMsg << " on line " << errLine << " column " << errCol << endl;
            }
        } else {
            out << "Could not open the specified file: " << xml_file << endl;
        }
    } else {
        out << "You must specify an XML file to load by using the -f= parameter." << endl;
    }

    if(report_name == "" || report_src == "") {
        // an error message already should have been displayed to the user
        exit(-1);
    }

    if (  (databaseURL != "") &&
          (username != "")    &&
          (passwd != "")          ) {
      QSqlDatabase db;

// Open the Database Driver
      db = databaseFromURL( databaseURL );
      if (!db.isValid())
      {
        out << "Could not load the specified database driver." << endl;
        exit(-1);
      }

//  Try to connect to the Database
      db.setUserName(username);
      db.setPassword(passwd);
      if (!db.open())
      {
        out << "Host=" << db.hostName() << ", Database=" << db.databaseName() << ", port=" << db.port() << endl;
        out << "Could not log into database.  System Error: "
            << db.lastError().text() << endl;
//.........这里部分代码省略.........
开发者ID:Wushaowei001,项目名称:xtuple,代码行数:101,代码来源:main.cpp

示例5: sImport

void ImportWindow::sImport()
{
  _log->append(tr("Import Started..."));
  QListWidgetItem * item = 0;
  QList<QListWidgetItem *> list = _reports->selectedItems();
  for(int i = 0; i < list.count(); i++)
  {
    item = list.at(i);
    QString xml_file = item->text();

    QString report_name  = QString::null;
    QString report_desc  = QString::null;
    QString report_src   = QString::null;
    int     report_grade = item->data(Qt::UserRole).toInt();

    if(!xml_file.isEmpty())
    {
      QFile file(xml_file);
      if(file.open(QIODevice::ReadOnly))
      {
        QDomDocument doc;
        QString errMsg;
        int errLine, errCol;
        if(doc.setContent(&file, &errMsg, &errLine, &errCol))
        {
          QDomElement root = doc.documentElement();
          if(root.tagName() == "report")
          {
            for(QDomNode n = root.firstChild();
                  !n.isNull(); n = n.nextSibling())
            {
              if(n.nodeName() == "name")
                report_name = n.firstChild().nodeValue();
              else if(n.nodeName() == "description")
                report_desc = n.firstChild().nodeValue();
            }
            report_src = doc.toString();

            if(!report_name.isEmpty())
            {
              QSqlQuery qry;
              QSqlQuery query;

              qry.prepare(getSqlFromTag("fmt09", QSqlDatabase::database().driverName()));	// MANU
              qry.bindValue(":report_name",  report_name);	// MANU
              qry.bindValue(":report_grade", report_grade);	// MANU
              qry.exec();
              if(qry.first())
              {
                // update
                query.prepare(getSqlFromTag("fmt10", QSqlDatabase::database().driverName()));	// MANU
                query.bindValue(":report_desc", report_desc);		// MANU
                query.bindValue(":report_src",   report_src);		// MANU
                query.bindValue(":report_id", qry.value(0));		// MANU
                query.bindValue(":report_name",  report_name);	// MANU
              }
              else
              {
                // insert
                query.prepare(getSqlFromTag("fmt11", QSqlDatabase::database().driverName()));	// MANU
                query.bindValue(":report_name",  report_name);	// MANU
                query.bindValue(":report_desc", report_desc);		// MANU
                query.bindValue(":report_src",   report_src);		// MANU
                query.bindValue(":report_grade", report_grade);	// MANU
              }
              
              if(!query.exec())
              {
                QSqlError err = query.lastError();
                _log->append(tr("<font color=red>The following error was encountered while trying to import %1 into the database:\n"
                                "\t%2\n\t%3\n</font>")
                              .arg(xml_file)
                              .arg(err.driverText())
                              .arg(err.databaseText()));
              }
              else
                _log->append(tr("Import successful of %1").arg(xml_file));
            }
            else
              _log->append(tr("<font color=orange>The document %1 does not have a report name defined\n</font>")
                            .arg(xml_file));
          }
          else
            _log->append(tr("<font color=red>XML Document %1 does not have root node of report\n</font>")
                          .arg(xml_file));
        }
        else
          _log->append(tr("<font color=red>Error parsing file %1: %2 on line %3 column %4\n</font>")
                        .arg(xml_file).arg(errMsg).arg(errLine).arg(errCol));
      }
      else
        _log->append(tr("<font color=red>Could not open the specified file: %1\n</font>")
                      .arg(xml_file));
    }
    else
      _log->append("<font color=red>Encountered and empty entry: No file name was given.\n</font>");
  }
  _log->append(tr("Import complete!\n\n\n"));
}
开发者ID:ChristopherCotnoir,项目名称:openrpt,代码行数:99,代码来源:importwindow.cpp

示例6: addTrasact

bool AbstractDocument::addTrasact(int artId, int storage, int storageOut,
                                  double count, double price, QString name,
                                  QString suborder, int mol, int transType, int formDirection)
{
    QSqlQuery sqlTransact;
    sqlTransact.prepare("INSERT INTO storage_transaction (tr_article,"
                        "tr_storage,tr_storage_out,tr_count_transac,"
                        "tr_count_current,tr_price_transac,tr_price_current,"
                        "tr_document,tr_type,tr_name,tr_mol,tr_suborder,"
                        "tr_form_direction) VALUES ("
                        ":art,:storage,:storage_out,:count_tr,:count_cur,"
                        ":price_tr,:price_cur,:doc,:type,:name,:mol,:suborder,"
                        ":form_direction)");

    int direction_type = transType;

    if (transType == -1) {
        direction_type = count > 0
                         ? TransactionType::In
                         : TransactionType::Out;
    }

    double currCount = 0.0;
    double currPrice = 0.0;

    QSqlQuery sql;

    if (formDirection == 1) {
        sql.exec(QString("SELECT tr_count_current,tr_price_current FROM current_balance_n "
                         "WHERE tr_article = %1 AND tr_storage = %2 AND tr_form_direction = %3")
                 .arg(artId)
                 .arg(storage)
                 .arg(formDirection));
    } else if (formDirection == 2) {
        sql.exec(QString("SELECT tr_count_current,tr_price_current FROM current_balance_mol "
                         "WHERE tr_article = %1 AND tr_mol = %2 AND tr_suborder = '%4' AND tr_form_direction = %3")
                 .arg(artId)
                 .arg(mol)
                 .arg(formDirection)
                 .arg(suborder));
    }
    if (direction_type == TransactionType::Inventarize && count == 0) {
    } else {
        if (sql.next()) {
            currCount = sql.value(0).toDouble();
            currPrice = sql.value(1).toDouble();
        }
    }


    sqlTransact.bindValue(":art",artId);
    sqlTransact.bindValue(":storage",storage);
    sqlTransact.bindValue(":storage_out",storageOut);
    sqlTransact.bindValue(":count_tr",count < 0 ? - count : count);
    sqlTransact.bindValue(":count_cur",currCount + count);
    sqlTransact.bindValue(":price_tr",price);
    sqlTransact.bindValue(":price_cur",currCount + count != 0
                          ? ((currCount * currPrice) +
                             (count * price))/
                          (currCount + count)
                          : 0);

    sqlTransact.bindValue(":doc",_id);
    sqlTransact.bindValue(":type",direction_type);
    sqlTransact.bindValue(":name",name);
    sqlTransact.bindValue(":mol",mol);
    sqlTransact.bindValue(":suborder",suborder);
    sqlTransact.bindValue(":form_direction",formDirection);
    sqlTransact.exec();

    if (sqlTransact.lastError().isValid()) {
        _error = sqlTransact.lastError();
        return false;
    }

    return true;
}
开发者ID:wulff007,项目名称:FastStorage,代码行数:77,代码来源:documenttypes.cpp

示例7: writeToDB

int LoadPriv::writeToDB(const QString pkgname, QString &errMsg)
{
  if (_name.isEmpty())
  {
    errMsg = TR("<font color=orange>The Privilege does not have a name.</font>")
               .arg(_name);
    return -1;
  }

  if (_module.isEmpty())
  {
    errMsg = TR("<font color=orange>The Privilege %1 has not been "
                 "assigned to a module and so may not be assignable.</font>")
               .arg(_name);
  }

  QSqlQuery select;
  QSqlQuery upsert;

  int privid    = -1;
  int pkgheadid = -1;
  int pkgitemid = -1;
  if (pkgname.isEmpty())
    select.prepare(QString("SELECT priv_id, -1, -1"
                           "  FROM %1priv "
                           " WHERE (priv_name=:name);")
                      .arg(_system ? "" : "pkg"));
  else
    select.prepare(_pkgitemQueryStr);
  select.bindValue(":name",    _name);
  select.bindValue(":pkgname", pkgname);
  select.bindValue(":type",    _pkgitemtype);
  select.exec();
  if(select.first())
  {
    privid    = select.value(0).toInt();
    pkgheadid = select.value(1).toInt();
    pkgitemid = select.value(2).toInt();
  }
  else if (select.lastError().type() != QSqlError::NoError)
  {
    QSqlError err = select.lastError();
    errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
    return -5;
  }

  if (privid >= 0)
    upsert.prepare(QString("UPDATE %1priv "
                           "   SET priv_module=:module, "
                           "       priv_descrip=:comment "
                           " WHERE (priv_id=:id); ")
              .arg(_system ? "" : "pkg"));
  else
  {
    upsert.prepare("SELECT NEXTVAL('priv_priv_id_seq');");
    upsert.exec();
    if (upsert.first())
      privid = upsert.value(0).toInt();
    else if (upsert.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = upsert.lastError();
      errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
      return -6;
    }
    upsert.prepare(QString("INSERT INTO %1priv ("
                           "       priv_id, priv_module, priv_name, priv_descrip "
                           ") VALUES (:id, :module, :name, :comment);")
              .arg(_system ? "" : "pkg"));
  }

  upsert.bindValue(":id",      privid);
  upsert.bindValue(":module",  _module);
  upsert.bindValue(":name",    _name);
  upsert.bindValue(":comment", _comment);

  if (!upsert.exec())
  {
    QSqlError err = upsert.lastError();
    errMsg = _sqlerrtxt.arg(_name).arg(err.driverText()).arg(err.databaseText());
    return -7;
  }

  if (pkgheadid >= 0)
  {
    int tmp = upsertPkgItem(pkgitemid, pkgheadid, privid, errMsg);
    if (tmp < 0)
      return tmp;
  }

  return privid;
}
开发者ID:gpazo,项目名称:xtuple-svn,代码行数:91,代码来源:loadpriv.cpp

示例8: savaFun

void CustomsManage::savaFun()
{
    QSqlQuery query;
    if(nameLineEdit->text().isEmpty())
    {
        QMessageBox::warning(this,"警告","请输入客户的姓名");
        return;
    }

    switch(oper)
    {
    case 1:
    {


        QString update_sql="update customs set name =:name, company =:company ,  address =:address ,\
                phonenumber =:phonenumber  , customstype =:customstype  where id = :updatedId";
        query.prepare(update_sql);
        query.bindValue(":updatedId",updatedId);
        qDebug() << updatedId;
        query.bindValue(":name", nameLineEdit->text());
        query.bindValue(":company", companyLineEdit->text());
        query.bindValue(":address",addressLineEdit->text() );
        query.bindValue(":phonenumber",phonenumLineEdit->text());
        query.bindValue(":customstype", customstypeComboBox->currentText());

        if(!query.exec())
        {
            qDebug() << query.lastError();
            resetFun();
        }
        else
        {
            msgLabel->setText("<h3><font color=red>客户信息修改成功!</font></h3>");

            tableModel->item(rowNum, 1)->setText(nameLineEdit->text());
            tableModel->item(rowNum, 2)->setText(companyLineEdit->text());
            tableModel->item(rowNum, 3)->setText(addressLineEdit->text());
            tableModel->item(rowNum, 4)->setText(phonenumLineEdit->text());
            tableModel->item(rowNum, 5)->setText(customstypeComboBox->currentText());
            resetFun();
        }

            oper=0;
            break;
    }
    case 0:
    {
        msgLabel->setText("<h3><font color=red>当前操作:添加客户信息</font></h3>");
        QString insert_sql = "insert into customs(name ,company, address,phonenumber, customstype )  values (?,?,?,?,?)";//


        query.prepare(insert_sql);

        query.addBindValue(nameLineEdit->text());
        query.addBindValue(companyLineEdit->text());
        query.addBindValue(addressLineEdit->text());
        query.addBindValue(phonenumLineEdit->text());
        query.addBindValue(customstypeComboBox->currentText());

        if(!query.exec())
        {
            qDebug() << query.lastError();
            resetFun();
        }
        else
        {
            int rowCount=tableModel->rowCount();
            tableModel->setItem(rowCount,0,new QStandardItem(query.lastInsertId().toString()));
            tableModel->setItem(rowCount,1,new QStandardItem(nameLineEdit->text()));
            tableModel->setItem(rowCount,2,new QStandardItem(companyLineEdit->text()));
            tableModel->setItem(rowCount,3,new QStandardItem(addressLineEdit->text()));
            tableModel->setItem(rowCount,4,new QStandardItem(phonenumLineEdit->text()));
            tableModel->setItem(rowCount,5,new QStandardItem(customstypeComboBox->currentText()));

            msgLabel->setText("<h3><font color=red>商品信息添加成功!</font></h3>");
            resetFun();
        }

    break;
    }
    }

}
开发者ID:gqqcode,项目名称:warehouse-management-system,代码行数:84,代码来源:customsmanage.cpp

示例9: text

void
FormMain::folderChanged( QTreeWidgetItem * current, QTreeWidgetItem * )
{
	editInfo->clear();

	if ( ! current )
		return;

	const int folder_id = current->data( 0, Qt::UserRole ).toInt();

	QString text("Folder: ");

	QSqlQuery q;

	// self
	q.prepare("SELECT "
			"name, "
			"path, "
			"size "
		"FROM "
			"folders "
		"WHERE "
			"id = :id ");

	q.bindValue(":id", folder_id );

	if ( q.exec() ) {
		if ( q.first() )
			text += q.value( 0 ).toString() + "<BR>" +
				"Path: " + q.value( 1 ).toString() + "<BR>" +
				"Size: " + prettyPrint( q.value( 2 ).toLongLong() ) + "<BR>";

	} else {
		emit yell( q.lastError().text() );
		return;
	}

	// count of folders
	int folderCount = 0;
	countFolders( folder_id, folderCount );

	// count of types
	int typeCount = 0;
	QHash< QString, int > types;
	countTypes( folder_id, types, typeCount );

	// ordering
	QMultiMap< int, QString > typesMap;
	QHash< QString, int >::const_iterator h = types.constBegin();

	while ( h != types.constEnd() ) {
		typesMap.insert( h.value(), h.key() );
		++h;
	}

	// percent of folders
	text += tr("folders: %1 (%2%)<BR>")
		.arg( folderCount )
		.arg( folderCount / ( qreal )( folderCount + typeCount ) * 100., 0, 'f', 1 );

	// percents of files

	chart->clear();

	if ( typesMap.count() > 0 ) {
		QMultiMap< int, QString >::const_iterator mm = typesMap.constEnd();

		do {
			--mm;

			const qreal percent = mm.key() / ( qreal )( folderCount + typeCount ) * 100;

			text += tr("%1: %2 (%3%)<BR>")
				.arg( mm.value() )
				.arg( mm.key() )
				.arg( percent, 0, 'f', 1 );

			chart->addPiece( percent, mm.value() );

		} while ( mm != typesMap.constBegin() );
	}

	text += QString( 50, '-' ) + "<BR>";		// horizontal line -------

	// folders
	text += "<BR><B>folders:</B><BR>";

	q.prepare("SELECT "
			"name, "
			"size "
		"FROM "
			"folders "
		"WHERE "
			"parent_id = :id "
		"ORDER BY "
			"size DESC");

	q.bindValue(":id", folder_id );

	if ( q.exec() ) {
//.........这里部分代码省略.........
开发者ID:masakra,项目名称:folderchart,代码行数:101,代码来源:FormMain.cpp

示例10: loadSqlMembers

void SecurityManager::loadSqlMembers() {

    QSqlQuery query;

    query.setForwardOnly(true);

    query.exec("select * from trainers limit 1");

    int count = query.record().count();

    if (count == 8) {
        /* Outdated database, we are going to add ban time */
        QSqlDatabase::database().transaction();

        query.exec("alter table trainers add column ban_expire_time int");
        query.exec("update trainers set ban_expire_time=0");
        //query.exec("create index ban_expire_time_index on trainers (ban_expire_time)");

        QSqlDatabase::database().commit();
    } else if (!query.next()) {
        if (SQLCreator::databaseType == SQLCreator::PostGreSQL) {
            /* The only way to have an auto increment field with PostGreSQL is to my knowledge using the serial type */
            query.exec("create table trainers (id serial, "
                       "name varchar(20), laston char(19), auth int, banned boolean,"
                       "salt varchar(7), hash varchar(32), ip varchar(39), ban_expire_time int, primary key(id), unique(name))");
        } else if (SQLCreator::databaseType == SQLCreator::MySQL) {
            query.exec("CREATE TABLE IF NOT EXISTS trainers (id int(11) NOT NULL auto_increment, "
                       "name varchar(20), laston char(19), auth int(11), banned bool, "
                       "salt varchar(7), hash varchar(32), ip varchar(39), "
                       "ban_expire_time int(11), PRIMARY KEY (id));");
        } else if (SQLCreator::databaseType == SQLCreator::SQLite){
            /* The only way to have an auto increment field with SQLite is to my knowledge having a 'integer primary key' field -- that exact quote */
            query.exec("create table trainers (id integer primary key autoincrement, name varchar(20) unique, "
                       "laston char(19), auth int, banned boolean, salt varchar(7), hash varchar(32), "
                       "ip varchar(39), ban_expire_time int);");
        } else {
            throw QString("Using a not supported database");
        }

        query.exec("create index tname_index on trainers (name)");
        query.exec("create index tip_index on trainers (ip)");

        QFile memberFile("serverdb/members.txt");
        if (memberFile.exists()) {
            Server::print("importing text db");

            if (!memberFile.open(QFile::ReadWrite)) {
                throw QObject::tr("Error: cannot open the file that contains the members ");
            }

            clock_t t = clock();

            query.prepare("insert into trainers(name, laston, auth,  banned, salt, hash, ip, ban_expire_time) values (:name, :laston, :auth,"
                          ":banned, :salt, :hash, :ip, :banexpire)");

            QSqlDatabase::database().transaction();
            int counter = 0;
            while (!memberFile.atEnd()) {
                if (query.lastError().isValid() && counter > 0) {
                    Server::print(QString("Error in last query (number %1): %2").arg(counter).arg(query.lastError().text()));
                    break;
                }

                ++counter;

                if (counter % 1000 == 0) {
                    Server::print(QString("Loaded %1 members so far...").arg(counter));
                }

                QByteArray arr = memberFile.readLine();
                QString s = QString::fromUtf8(arr.constData(), std::max(0,arr.length()-1)); //-1 to remove the \n

                QStringList ls = s.split('%');

                if (ls.size() >= 6 && isValid(ls[0])) {
                    query.bindValue(":name", ls[0].toLower());
                    query.bindValue(":laston",ls[1]);
                    query.bindValue(":auth", ls[2][0].toLatin1()-'0');
                    query.bindValue(":banned", ls[2][1] == '1');
                    /* Weirdly, i seem to have problems when updating something that has a salt containing \, probably postgresql driver,
                       so i remove them. */
                    if (!ls[3].contains('\\')) {
                        query.bindValue(":salt", ls[3].trimmed().toLatin1());
                        query.bindValue(":hash", ls[4].trimmed().toLatin1());
                    } else {
                        query.bindValue(":salt", "");
                        query.bindValue(":hash", "");
                    }
                    query.bindValue(":ip", ls[5].trimmed());
                    if (ls.size() >= 7) {
                        query.bindValue(":banexpire", ls[6]);
                    } else {
                        query.bindValue(":banexpire", 0);
                    }
                    query.exec();
                }
            }

            QSqlDatabase::database().commit();

//.........这里部分代码省略.........
开发者ID:Jirachier,项目名称:pokemon-online,代码行数:101,代码来源:security.cpp

示例11: parseTrack


//.........这里部分代码省略.........
    QString path;
    QString filename;
    QString location;
    float bpm = 0.0;
    int bitrate = 0;
    QString key;
    //duration of a track
    int playtime = 0;
    int rating = 0;
    QString comment;
    QString tracknumber;

    //get XML attributes of starting ENTRY tag
    QXmlStreamAttributes attr = xml.attributes ();
    title = attr.value("TITLE").toString();
    artist = attr.value("ARTIST").toString();

    //read all sub tags of ENTRY until we reach the closing ENTRY tag
    while (!xml.atEnd()) {
        xml.readNext();
        if (xml.isStartElement()) {
            if (xml.name() == "ALBUM") {
                QXmlStreamAttributes attr = xml.attributes ();
                album = attr.value("TITLE").toString();
                tracknumber = attr.value("TRACK").toString();
                continue;
            }
            if (xml.name() == "LOCATION") {
                QXmlStreamAttributes attr = xml.attributes ();
                volume = attr.value("VOLUME").toString();
                path = attr.value("DIR").toString();
                filename = attr.value("FILE").toString();
                // compute the location, i.e, combining all the values
                // On Windows the volume holds the drive letter e.g., d:
                // On OS X, the volume is supposed to be "Macintosh HD" at all times,
                // which is a folder in /Volumes/
                #if defined(__APPLE__)
                location = "/Volumes/"+volume;
                #else
                location = volume;
                #endif
                location += path.replace(QString(":"), QString(""));
                location += filename;
                continue;
            }
            if (xml.name() == "INFO") {
                QXmlStreamAttributes attr = xml.attributes();
                key = attr.value("KEY").toString();
                bitrate = attr.value("BITRATE").toString().toInt() / 1000;
                playtime = attr.value("PLAYTIME").toString().toInt();
                genre = attr.value("GENRE").toString();
                year = attr.value("RELEASE_DATE").toString();
                comment = attr.value("COMMENT").toString();
                QString ranking_str = attr.value("RANKING").toString();
                // A ranking in Traktor has ranges between 0 and 255 internally.
                // This is same as the POPULARIMETER tag in IDv2,
                // see http://help.mp3tag.de/main_tags.html
                //
                // Our rating values range from 1 to 5. The mapping is defined as follow
                // ourRatingValue = TraktorRating / 51
                 if (ranking_str != "" && qVariantCanConvert<int>(ranking_str)) {
                    rating = ranking_str.toInt()/51;
                 }
                continue;
            }
            if (xml.name() == "TEMPO") {
                QXmlStreamAttributes attr = xml.attributes ();
                bpm = attr.value("BPM").toString().toFloat();
                continue;
            }
        }
        //We leave the infinte loop, if twe have the closing tag "ENTRY"
        if (xml.name() == "ENTRY" && xml.isEndElement()) {
            break;
        }
    }

    // If we reach the end of ENTRY within the COLLECTION tag
    // Save parsed track to database
    query.bindValue(":artist", artist);
    query.bindValue(":title", title);
    query.bindValue(":album", album);
    query.bindValue(":genre", genre);
    query.bindValue(":year", year);
    query.bindValue(":duration", playtime);
    query.bindValue(":location", location);
    query.bindValue(":rating", rating);
    query.bindValue(":comment", comment);
    query.bindValue(":tracknumber", tracknumber);
    query.bindValue(":key", key);
    query.bindValue(":bpm", bpm);
    query.bindValue(":bitrate", bitrate);

    bool success = query.exec();
    if (!success) {
        qDebug() << "SQL Error in TraktorTableModel.cpp: line"
                 << __LINE__ << " " << query.lastError();
        return;
    }
}
开发者ID:abhinavtankha,项目名称:mixxx,代码行数:101,代码来源:traktorfeature.cpp

示例12: on_pushButton_save_clicked

void addoredir_raspisanie::on_pushButton_save_clicked()
{
    if (ui->comboBox_sotr->currentIndex() ==-1)
    {
        QMessageBox::warning(this, tr("Ошибка"), tr("Выберите сотрудника"));
        return;
    }
    if (! dal_main->checkConnection())
    {
        QMessageBox::warning(this, tr("Ошибка соединения"), tr("Соединение не установлено"));
        return;
    }
    QSqlQuery* insertQuery = new QSqlQuery();
    insertQuery->prepare("INSERT INTO is_raspisanie(sotr_id, den_nedeli, vremya, predmet) VALUES (:sotr_id, :den_nedeli, :vremya, :predmet)");
    insertQuery->bindValue(":sotr_id", ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt());

    if (!this->isEdit)
    {
        for (int den = 0; den < 6; den++)
        {
            for (int i = 0; i < 7; i++)
            {
                QString vr = ui->tableWidget_rasp->item(i, 0)->text();
                QString pr = ui->tableWidget_rasp->item(i, den+1)->text();
                if(pr.isEmpty())
                    pr = "-";
                insertQuery->bindValue(":den_nedeli", days.at(den));
                insertQuery->bindValue(":vremya", vr);
                insertQuery->bindValue(":predmet", pr);
                insertQuery->exec();
            }
        }
        QMessageBox::information(this, tr("Информация"), tr("Запись успешно добавлена"));
    }
    else
    {
        QSqlQuery* deleteQuery = new QSqlQuery;
        int id = ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt();
        deleteQuery->prepare("DELETE FROM is_raspisanie WHERE sotr_id = " + QString::number(id));
        deleteQuery->exec();
        qDebug()<<ui->comboBox_sotr->model()->index(ui->comboBox_sotr->currentIndex(),0).data().toInt()<<deleteQuery->executedQuery()<<deleteQuery->lastError();
        for (int den = 0; den < 6; den++)
        {
            for (int i = 0; i < 7; i++)
            {
                QString vr = ui->tableWidget_rasp->item(i, 0)->text();
                QString pr = ui->tableWidget_rasp->item(i, den+1)->text();
                if(pr.isEmpty())
                    pr = "-";
                insertQuery->bindValue(":den_nedeli", days.at(den));
                insertQuery->bindValue(":vremya", vr);
                insertQuery->bindValue(":predmet", pr);
                insertQuery->exec();
            }
        }
        QMessageBox::information(this, tr("Информация"), tr("Данные успешно отредактированы"));

    }
    this->close();
}
开发者ID:kanbodows,项目名称:kafpocs,代码行数:60,代码来源:addoredir_raspisanie.cpp

示例13: on_listWidget_itemDoubleClicked

void RecipeWidget::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
    ui->optionButton->setEnabled(true);
    int id = item->data(Qt::UserRole).toInt();
    this->current_id = id;
    QSqlQuery query;
    if(query.exec("SELECT * FROM Recipe WHERE id="+QString::number(id)+";")){
        query.next();
        ui->stackedWidget->setCurrentIndex(1);
        ui->backButton->setEnabled(true);
        ui->nameLabel->setText(query.value(1).toString()); //name
        ui->typeLabel->setText(query.value(2).toString()); //type
        ui->preparationText->setText(query.value(3).toString());
        QSqlQuery subquery;
        QString subquerytext = "SELECT Ingredient.amount, Ingredient.verbose_name, Ingredient.food_id "
                         "FROM Ingredient JOIN Recipe WHERE Ingredient.recipe_id=Recipe.id "
                         "AND Recipe.id="+QString::number(id)+";";
        bool canCook=true;
        if(subquery.exec(subquerytext)){
            ui->ingredientText->clear();
            while(subquery.next()){
                ui->ingredientText->insertPlainText(subquery.value(0).toString()+" "+subquery.value(1).toString());
                //check if there is enough of this on the fridge and add the right icon
                QSqlQuery subsubquery;
                subsubquery.prepare("SELECT amount FROM Item WHERE food_id=?");
                subsubquery.addBindValue(subquery.value(2).toInt());
                if(subsubquery.exec()){
                    int amount = 0;
                    while(subsubquery.next()){
                        amount+=subsubquery.value(0).toInt();
                    }
                    if(amount>=subquery.value(0).toInt()){
                        ui->ingredientText->insertHtml("<img src=\":/res/checkicon.png\" height=\"20\" width=\"20\"><br>");
                    }else{
                        canCook=false;
                        ui->ingredientText->insertHtml("<img src=\":/res/noicon.png\" height=\"20\" width=\"20\"><br>");
                    }
                }else{
                    qDebug()<<subsubquery.lastError().text();
                    ui->ingredientText->insertPlainText("\n");
                }
            }
            subquery.prepare("SELECT VerboseIngredient.verbose_name FROM VerboseIngredient JOIN Recipe WHERE VerboseIngredient.recipe_id=Recipe.id AND Recipe.id=?");
            subquery.addBindValue(id);
            if(subquery.exec()){
                while(subquery.next()){
                    ui->ingredientText->insertPlainText(subquery.value(0).toString());
                    //set ok icon
                    ui->ingredientText->insertHtml("<img src=\":/res/checkicon.png\" height=\"20\" width=\"20\"><br>");

                }
            }
        if(canCook){
            ui->statusLabel->setText("Todos los ingredientes disponibles!");
            ui->optionButton->setIcon(QIcon(":/res/cookicon.png"));
            ui->optionButton->setText("Preparar esta receta");
        }else{
            ui->statusLabel->setText("Faltan ingredientes!");
            ui->optionButton->setIcon(QIcon(":/res/listrecipeicon.png"));
            ui->optionButton->setText("Agregar a la lista de compras");
        }
        }else{
            qDebug()<<"Couldn't retrieve ingredientes";
            qDebug()<<subquery.lastError().text();
        }
    }else{
        qDebug()<<"Couldn't retrieve recipe from database";
    }


}
开发者ID:jesusgp22,项目名称:Icemart,代码行数:71,代码来源:recipewidget.cpp

示例14: insert


//.........这里部分代码省略.........
    //Check if patient is already present in the db
    check_exists_query.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" );
    check_exists_query.bindValue ( 0, QString ( patientID.c_str() ) );
    check_exists_query.bindValue ( 1, QString ( patientsName.c_str() ) );
    check_exists_query.exec();
    
    if (check_exists_query.next())
      {
      patientUID = check_exists_query.value(check_exists_query.record().indexOf("UID")).toInt();
      }
    else
      {
      // Insert it
      QSqlQuery statement ( d->db );
      statement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" );
      statement.bindValue ( 0, QString ( patientsName.c_str() ) );
      statement.bindValue ( 1, QString ( patientID.c_str() ) );
      statement.bindValue ( 2, QString ( patientsBirthDate.c_str() ) );
      statement.bindValue ( 3, QString ( patientsBirthTime.c_str() ) );
      statement.bindValue ( 4, QString ( patientsSex.c_str() ) );
      statement.bindValue ( 5, QString ( patientsAge.c_str() ) );
      statement.bindValue ( 6, QString ( patientComments.c_str() ) );
      statement.exec ();
      patientUID = statement.lastInsertId().toInt();
      logger.debug ( "New patient inserted: " + QString().setNum ( patientUID ) );
      }
    }

  if ( studyInstanceUID != "" )
    {
    check_exists_query.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" );
    check_exists_query.bindValue ( 0, QString ( studyInstanceUID.c_str() ) );
    check_exists_query.exec();
    if(!check_exists_query.next())
      {
      QSqlQuery statement ( d->db );
      statement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
      statement.bindValue ( 0, QString ( studyInstanceUID.c_str() ) );
      statement.bindValue ( 1, patientUID );
      statement.bindValue ( 2, QString ( studyID.c_str() ) );
      statement.bindValue ( 3, QDate::fromString ( studyDate.c_str(), "yyyyMMdd" ) );
      statement.bindValue ( 4, QString ( studyTime.c_str() ) );
      statement.bindValue ( 5, QString ( accessionNumber.c_str() ) );
      statement.bindValue ( 6, QString ( modalitiesInStudy.c_str() ) );
      statement.bindValue ( 7, QString ( institutionName.c_str() ) );
      statement.bindValue ( 8, QString ( referringPhysician.c_str() ) );
      statement.bindValue ( 9, QString ( performingPhysiciansName.c_str() ) );
      statement.bindValue ( 10, QString ( studyDescription.c_str() ) );
      if ( !statement.exec() )
        {
        logger.error ( "Error executing statament: " + statement.lastQuery() + " Error: " + statement.lastError().text() );
        }
      }
    }

  if ( seriesInstanceUID != "" )
    {
    check_exists_query.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" );
    check_exists_query.bindValue ( 0, QString ( seriesInstanceUID.c_str() ) );
    logger.warn ( "Statement: " + check_exists_query.lastQuery() );
    check_exists_query.exec();
    if(!check_exists_query.next())
      {
      QSqlQuery statement ( d->db );
      statement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
      statement.bindValue ( 0, QString ( seriesInstanceUID.c_str() ) );
      statement.bindValue ( 1, QString ( studyInstanceUID.c_str() ) );
      statement.bindValue ( 2, static_cast<int>(seriesNumber) );
      statement.bindValue ( 3, QString ( seriesDate.c_str() ) );
      statement.bindValue ( 4, QDate::fromString ( seriesTime.c_str(), "yyyyMMdd" ) );
      statement.bindValue ( 5, QString ( seriesDescription.c_str() ) );
      statement.bindValue ( 6, QString ( bodyPartExamined.c_str() ) );
      statement.bindValue ( 7, QString ( frameOfReferenceUID.c_str() ) );
      statement.bindValue ( 8, static_cast<int>(acquisitionNumber) );
      statement.bindValue ( 9, QString ( contrastAgent.c_str() ) );
      statement.bindValue ( 10, QString ( scanningSequence.c_str() ) );
      statement.bindValue ( 11, static_cast<int>(echoNumber) );
      statement.bindValue ( 12, static_cast<int>(temporalPosition) );
      if ( !statement.exec() )
        {
        logger.error ( "Error executing statament: " + statement.lastQuery() + " Error: " + statement.lastError().text() );
        }
      }
    }
  if ( !filename.isEmpty() )
    {
    check_exists_query.prepare ( "SELECT * FROM Images WHERE Filename = ?" );
    check_exists_query.bindValue ( 0, filename );
    check_exists_query.exec();
    if(!check_exists_query.next())
      {
      QSqlQuery statement ( d->db );
      statement.prepare ( "INSERT INTO Images ( 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ? )" );
      statement.bindValue ( 0, filename );
      statement.bindValue ( 1, QString ( seriesInstanceUID.c_str() ) );
      statement.bindValue ( 2, QDateTime::currentDateTime() );
      statement.exec();
      }
    }
}
开发者ID:benoitbleuze,项目名称:CTK,代码行数:101,代码来源:ctkDICOMIndexerBase.cpp

示例15: importTrack

void RhythmboxFeature::importTrack(QXmlStreamReader &xml, QSqlQuery &query) {
    QString title;
    QString artist;
    QString album;
    QString year;
    QString genre;
    QString location;
    QUrl locationUrl;

    int bpm = 0;
    int bitrate = 0;

    //duration of a track
    int playtime = 0;
    int rating = 0;
    QString comment;
    QString tracknumber;

    while (!xml.atEnd()) {
        xml.readNext();
        if (xml.isStartElement()) {
            if (xml.name() == "title") {
                title = xml.readElementText();
                continue;
            }
            if (xml.name() == "artist") {
                artist = xml.readElementText();
                continue;
            }
            if (xml.name() == "genre") {
                genre = xml.readElementText();
                continue;
            }
            if (xml.name() == "album") {
                album = xml.readElementText();
                continue;
            }
            if (xml.name() == "track-number") {
                tracknumber = xml.readElementText();
                continue;
            }
            if (xml.name() == "duration") {
                playtime = xml.readElementText().toInt();;
                continue;
            }
            if (xml.name() == "bitrate") {
                bitrate = xml.readElementText().toInt();
                continue;
            }
            if (xml.name() == "beats-per-minute") {
                bpm = xml.readElementText().toInt();
                continue;
            }
            if (xml.name() == "comment") {
                comment = xml.readElementText();
                continue;
            }
            if (xml.name() == "location") {
                locationUrl = QUrl::fromEncoded( xml.readElementText().toUtf8());
                continue;
            }
        }
        //exit the loop if we reach the closing <entry> tag
        if (xml.isEndElement() && xml.name() == "entry") {
            break;
        }
    }

    location = locationUrl.toLocalFile();

    if (location.isEmpty()) {
        // here in case of smb:// location
        // TODO(XXX) QUrl does not support SMB:// locations does Mixxx?
        // use ~/.gvfs location instead
        return;
    }

    query.bindValue(":artist", artist);
    query.bindValue(":title", title);
    query.bindValue(":album", album);
    query.bindValue(":genre", genre);
    query.bindValue(":year", year);
    query.bindValue(":duration", playtime);
    query.bindValue(":location", location);
    query.bindValue(":rating", rating);
    query.bindValue(":comment", comment);
    query.bindValue(":tracknumber", tracknumber);
    query.bindValue(":bpm", bpm);
    query.bindValue(":bitrate", bitrate);

    bool success = query.exec();

    if (!success) {
        qDebug() << "SQL Error in rhythmboxfeature.cpp: line" << __LINE__
                 << " " << query.lastError();
        return;
    }
}
开发者ID:Adna1206,项目名称:mixxx,代码行数:98,代码来源:rhythmboxfeature.cpp


注:本文中的QSqlQuery::lastError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。