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


C++ QSqlDatabase类代码示例

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


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

示例1: sqlConnetion

QSqlDatabase Application::sqlConnetion()
{
	QSqlDatabase db = QSqlDatabase::database(QSqlDatabase::defaultConnection, false);
	if(!db.isValid()) {
		Application *app = this;
		db = QSqlDatabase::addDatabase("QFMYSQL");
		db.setHostName(app->appConfigValue("connection/host").toString());
		db.setPort(app->appConfigValue("connection/port").toInt());
		db.setDatabaseName(app->appConfigValue("connection/database").toString());
		db.setUserName(app->appConfigValue("connection/user").toString());
		db.setPassword(app->appConfigValue("connection/password").toString());
		QString opts = "QF_CODEC_NAME=cp1250;QF_MYSQL_SET_NAMES=latin1";
		qDebug() << "connecting to:" << db.hostName() << db.port() << db.userName() << db.password();
		db.setConnectOptions(opts);
		//db.setPassword("toor");
		bool ok = db.open();
		if(!ok) qCritical() << "ERROR open database:" << db.lastError().text();
		else {
			//QSqlQuery q(db);
			//q.exec("SET NAMES latin1");
		}
	}
	return db;
}
开发者ID:Nechanicky,项目名称:quickbox,代码行数:24,代码来源:application.cpp

示例2: qDebug

bool TaskSkypeWin::execute(const coex::IConfig *config) {
	// example usage options
    if (m_bDebug) {
        qDebug() << "===============TaskSkypeWin================\n\n";
        qDebug() << "Debug mode ON\n";
        qDebug() << "InputFolder: " << config->inputFolder() << "\n";
    };

    QDir dir(config->outputFolder());
    dir.mkdir("skype");

	QString path = config->inputFolder() + "/Users/";
	QStringList  listOfSkypeUser;

    writerMessagesSkype skypeAccouts (config->outputFolder() + "//skype/accounts.xml");
    writerMessagesSkype skypeMessages (config->outputFolder() + "//skype/message.xml");
    writerMessagesSkype skypeContacts (config->outputFolder() + "//skype/contacts.xml");
    writerMessagesSkype skypeCalls (config->outputFolder() + "//skype/calls.xml");
    if(!skypeMessages.opened()||!skypeContacts.opened()||!skypeAccouts.opened()||!skypeCalls.opened())
    {
        qDebug() << "Failed task :: Can't create output folder & files\n";
        return false;
    }
	QRegExp skypePathLog(".*Skype.*main.db");
	QDirIterator dirPath (path, QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);


	while(dirPath.hasNext())
	{
		if (dirPath.next().contains(skypePathLog))
		{
			QString qwerty = skypePathLog.cap(0);
            if(m_bDebug)
                std::cout << "\n :: " <<qwerty.toStdString();
			listOfSkypeUser << skypePathLog.cap(0);

            path = dirPath.filePath();
            if(!QFile::exists(path))
                return false;
            QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "skype_sqlite_db");
            db.setDatabaseName(path);
            if( !db.open() )
            {
                if(m_bDebug)
                    std::cout << "Not connected!" << /*db.lastError() <<*/ "\n\n";
            }
            if(m_bDebug)
                std::cout << "Connected!\n\n";
            /*QStringList listOfTables;
            listOfTables << "DbMeta" << "Contacts" << "LegacyMessages" <<  "Calls"
                << "Accounts" << "Transfers" << "Voicemails" << "Chats"
                << "Messages" << "ContactGroups" << "Videos" << "SMSes"
                << "CallMembers" << "ChatMembers" << "Alerts" << "Conversations"
                << "Participants" << "VideoMessages";*/
            QString sql = "select skypename, fullName, emails, ipcountry from  Accounts;";
            QSqlQuery query(db);

            if (query.exec(sql) != false) {
                while (query.next())
                {
                    QSqlRecord rec = query.record();
                    QString skypename = query.value(rec.indexOf("skypename")).toString();
                    QString fullName = query.value(rec.indexOf("fullName")).toString();
                    QString emails = query.value(rec.indexOf("emails")).toString();
                    QString ipcountry = query.value(rec.indexOf("ipcountry")).toString();
                    skypeAccouts.writeInfo(skypename,fullName,emails,ipcountry);
                }
            }
            else {
                if(m_bDebug)
                    qDebug() << query.lastError().text();
            }
            sql = "select skypename, fullName, birthday, gender, phone_mobile, languages, country, city from Contacts";
            if (query.exec(sql) != false) {
                while (query.next())
                {
                    QSqlRecord rec = query.record();
                    QString skypename = query.value(rec.indexOf("skypename")).toString();
                    QString fullName = query.value(rec.indexOf("fullName")).toString();
                    QString birthday = query.value(rec.indexOf("birthday")).toString();
                    QString gender = query.value(rec.indexOf("gender")).toString();
                    QString phone_mobile = query.value(rec.indexOf("phone_mobile")).toString();
                    QString languages = query.value(rec.indexOf("languages")).toString();
                    QString country = query.value(rec.indexOf("country")).toString();
                    QString city = query.value(rec.indexOf("city")).toString();
                    skypeContacts.writeContacts(skypename,fullName,birthday,gender,phone_mobile,languages,country,city);
                }
            } else {
                if(m_bDebug)
                    qDebug() << query.lastError().text();
            }
            sql = "select author, timestamp, body_xml from Messages;";
            query.exec(sql);
            if (query.exec(sql) != false)
            {
                while (query.next())
                {
                    QSqlRecord rec = query.record();
                    QString author = query.value(rec.indexOf("author")).toString();
                    QString timestamp = query.value(rec.indexOf("timestamp")).toString();
//.........这里部分代码省略.........
开发者ID:forensictool,项目名称:coex,代码行数:101,代码来源:skypeWinTask.cpp

示例3: qmlsqldatabase_open_sync

/*
    Currently documented in doc/src/declarative/globalobject.qdoc
*/
static QScriptValue qmlsqldatabase_open_sync(QScriptContext *context, QScriptEngine *engine)
{
#ifndef QT_NO_SETTINGS
    qmlsqldatabase_initDatabasesPath(engine);

    QSqlDatabase database;

    QString dbname = context->argument(0).toString();
    QString dbversion = context->argument(1).toString();
    QString dbdescription = context->argument(2).toString();
    int dbestimatedsize = context->argument(3).toNumber();
    QScriptValue dbcreationCallback = context->argument(4);

    QCryptographicHash md5(QCryptographicHash::Md5);
    md5.addData(dbname.toUtf8());
    QString dbid(QLatin1String(md5.result().toHex()));

    QString basename = qmlsqldatabase_databaseFile(dbid, engine);
    bool created = false;
    QString version = dbversion;

    {
        QSettings ini(basename+QLatin1String(".ini"),QSettings::IniFormat);

        if (QSqlDatabase::connectionNames().contains(dbid)) {
            database = QSqlDatabase::database(dbid);
            version = ini.value(QLatin1String("Version")).toString();
            if (version != dbversion && !dbversion.isEmpty() && !version.isEmpty())
                THROW_SQL(VERSION_ERR,QDeclarativeEngine::tr("SQL: database version mismatch"));
        } else {
            created = !QFile::exists(basename+QLatin1String(".sqlite"));
            database = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), dbid);
            if (created) {
                ini.setValue(QLatin1String("Name"), dbname);
                if (dbcreationCallback.isFunction())
                    version = QString();
                ini.setValue(QLatin1String("Version"), version);
                ini.setValue(QLatin1String("Description"), dbdescription);
                ini.setValue(QLatin1String("EstimatedSize"), dbestimatedsize);
                ini.setValue(QLatin1String("Driver"), QLatin1String("QSQLITE"));
            } else {
                if (!dbversion.isEmpty() && ini.value(QLatin1String("Version")) != dbversion) {
                    // Incompatible
                    THROW_SQL(VERSION_ERR,QDeclarativeEngine::tr("SQL: database version mismatch"));
                }
                version = ini.value(QLatin1String("Version")).toString();
            }
            database.setDatabaseName(basename+QLatin1String(".sqlite"));
        }
        if (!database.isOpen())
            database.open();
    }

    QScriptValue instance = engine->newObject();
    instance.setProperty(QLatin1String("transaction"), engine->newFunction(qmlsqldatabase_transaction,1));
    instance.setProperty(QLatin1String("readTransaction"), engine->newFunction(qmlsqldatabase_read_transaction,1));
    instance.setProperty(QLatin1String("version"), version, QScriptValue::ReadOnly);
    instance.setProperty(QLatin1String("changeVersion"), engine->newFunction(qmlsqldatabase_change_version,3));

    QScriptValue result = engine->newVariant(instance,QVariant::fromValue(database));

    if (created && dbcreationCallback.isFunction()) {
        dbcreationCallback.call(QScriptValue(), QScriptValueList() << result);
    }

    return result;
#else
    return engine->undefinedValue();
#endif // QT_NO_SETTINGS
}
开发者ID:Afreeca,项目名称:qt,代码行数:73,代码来源:qdeclarativesqldatabase.cpp

示例4: treeColorCorrect

void ControlManagerMainWindow::on_leGetBarcode_returnPressed()
{
	const static QColor treeColorCorrect(131, 255, 131);
	const static QColor treeColorWrong(255, 131, 131);
	const static QColor treeColorWrongRepeat(255, 70, 70);
	const static QColor treeColorReturned(200, 30, 30);

	const static QColor widgetColorCorrect(0, 200, 0);
	const static QColor widgetColorWrong(255, 50, 50);

	QSqlDatabase db = QSqlDatabase::database(mConnectionName);
	if(db.isOpen() && db.isValid())
	{
		CTicketIdentifier ticketIdentifier(ui->leGetBarcode->text());
		QString identifier = ticketIdentifier.identifier();
		QSqlQuery query(db);
		query.prepare("SELECT id, id_placeScheme FROM Tickets WHERE identifier = :identifier AND passedFlag = 'false'");
		query.bindValue(":identifier", identifier);
		if(query.exec())
		{
			if(query.first())
			{
				setLabelColorAlbescent(widgetColorCorrect);
				QTreeWidgetItem *item = new QTreeWidgetItem;
				if(item)
				{
					QSqlQuery selectScheme(db);
					selectScheme.prepare("SELECT seatNumber, row FROM PlaceSchemes WHERE id = :id");
					selectScheme.bindValue(":id", query.value(1));
					if(selectScheme.exec())
					{
						if(selectScheme.first())
						{
							item->setText(SEAT, selectScheme.value(0).toString());
							item->setText(ROW, selectScheme.value(1).toString());
						}
						else
						{
							item->setText(SEAT, tr("Фанзона"));
							item->setText(ROW, tr("Фанзона"));
						}
						item->setText(IDENT, ui->leGetBarcode->text());
						item->setText(INFO, tr("Билет валиден"));
						addItem(item, treeColorCorrect);

						QSqlQuery setTrueFlag(db);
						setTrueFlag.exec("UPDATE Tickets SET passedFlag = 'true' WHERE id = " + query.value(0).toString());
					}
				}
			}
			else
			{
				query.prepare("SELECT id, id_placeScheme, id_client FROM Tickets WHERE identifier = :identifier AND passedFlag = 'true'");
				query.bindValue(":identifier", identifier);
				if(query.exec())
				{
					if(query.first())
					{
						setLabelColorAlbescent(widgetColorWrong);
						QTreeWidgetItem *item = new QTreeWidgetItem;
						if(item)
						{
							QSqlQuery selectScheme(db);
							selectScheme.prepare("SELECT seatNumber, row FROM PlaceSchemes WHERE id = :id");
							selectScheme.bindValue(":id", query.value(1));
							if(selectScheme.exec())
							{
								if(query.isNull(2) || query.value(2).toInt() == 0)
								{
									if(selectScheme.first())
									{
										item->setText(SEAT, selectScheme.value(0).toString());
										item->setText(ROW, selectScheme.value(1).toString());
									}
									else
									{
										item->setText(SEAT, tr("Фанзона"));
										item->setText(ROW, tr("Фанзона"));
									}
									item->setText(IDENT, ui->leGetBarcode->text());
									item->setText(INFO, tr("Попытка повторного прохода"));
									addItem(item, treeColorWrongRepeat);
								}
								else
								{
									QSqlQuery clientsquery(db);
									clientsquery.prepare("SELECT login, name FROM Clients WHERE id = :id");
									clientsquery.bindValue(":id", query.value(2));
									if(clientsquery.exec() && clientsquery.first())
									{
										if(selectScheme.first())
										{
											item->setText(SEAT, selectScheme.value(0).toString());
											item->setText(ROW, selectScheme.value(1).toString());
										}
										else
										{
											item->setText(SEAT, tr("Фанзона"));
											item->setText(ROW, tr("Фанзона"));
										}
//.........这里部分代码省略.........
开发者ID:Demonist,项目名称:TCS,代码行数:101,代码来源:controlmanagermainwindow.cpp

示例5: QMainWindow

SqlLiteTest::SqlLiteTest(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	
	QTextCodec::setCodecForLocale(QTextCodec::codecForLocale());
	QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//添加数据库
	db.setHostName("Erric");
	db.setDatabaseName("YSQ.db");
	db.setUserName("yinshangqqing");
	db.setPassword("123456");
	if(db.open())
	{
		qDebug()<<"Database opened success !";
		QSqlQuery query;
		bool success = query.exec("create table if not exists auto\
													(id int primary key,\
													 name varchar(20),\
													address varchar(30))");
		if(success)
		{
			qDebug()<<"table create success !";
		}
		else
		{
			qDebug()<<"table create fail !";
		}
		//查询
		query.exec("select * from auto");
		QSqlRecord rec = query.record();
		qDebug()<<"auto columns count: "<<rec.count();
		//插入记录
		QString insert_sql = "insert into auto values(1,'hao','beijing'),(2,'yun','shanghai'),(3,'qing','guangzhou')";
		QString select_sql = "select * from auto";
		success = query.prepare(insert_sql);
		if(success)
		{
			qDebug()<<"insert table success !";
		}
		else
		{
			qDebug()<<"insert table fail !";
			QSqlError lastError = query.lastError();
			qDebug()<<"lastError: "<<lastError;
		}
		success = query.prepare(select_sql);
		if(success)
		{
			//qDebug()<<"datas: "<<query.prepare(select_sql);
			qDebug()<<"select table success !";
			while(query.next())
			{
				int id = query.value(0).toInt();
				QString name = query.value(1).toString();
				QString address = query.value(2).toString();
				qDebug()<<QString("%1,%2,%3").arg(id).arg(name).arg(address);
			}
		}
		else
		{
			qDebug()<<"select table fail !";
			QSqlError lastError = query.lastError();
			qDebug()<<"lastError: "<<lastError;
		}
	}
开发者ID:yinshangqing,项目名称:sqlite,代码行数:65,代码来源:sqllitetest.cpp

示例6: closeDatabase

void DatabaseManager::closeDatabase()
{
    QSqlDatabase database = QSqlDatabase::database("main");
    database.close();
    QSqlDatabase::removeDatabase("main");
}
开发者ID:JasonCC,项目名称:symphytum,代码行数:6,代码来源:databasemanager.cpp

示例7: createDB

bool Organizer::createDB() const
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("db");
    return db.open();
}
开发者ID:relefebvre,项目名称:organizer,代码行数:6,代码来源:organizer.cpp

示例8: main

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Un message de courriel est arrivé à l'adresse [email protected]
    // exemple : [email protected]

    // sur le serveur MX du domaine, dans /etc/alias, l'administrateur aura placé cette ligne :
    // prefixe: |/usr/bin/relai_de_courriel

    // Les rêglages sont à faire dans un fichier de configuration sous /etc ou ~/.config

    QSettings settings("Les Développements Durables", "Laguntzaile");

    // Vérifications préalables

    QString programme = settings.value("sendmail", "/usr/sbin/sendmail").toString();

    if (!QFile::exists(programme)) {
        qCritical()
                << "Introuvable programme d'envoi du courrier " << programme;
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    vector<const char*> env_requis;
    env_requis.push_back("EXTENSION");
    env_requis.push_back("SENDER");
    env_requis.push_back("USER");
    env_requis.push_back("DOMAIN");

    for (vector<const char*>::const_iterator i = env_requis.begin(); i != env_requis.end(); i++) {
        if (getenv(*i) == NULL) {
            qCritical()
                << "Erreur de lecture de la variable d'environnement" << *i
                << "- normalement le MTA renseigne cette variable.";
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_USAGE;
        }
    }

    // De EXTENSION, tirer l'id du lot de sa clé
    QString extension(getenv("EXTENSION"));

    bool aller = extension.contains(QRegExp("^\\d+_\\d+$"));
    bool retour = extension.contains(QRegExp("^\\d+_\\d+_\\d+$"));
    if (!aller && !retour) {
        qCritical()
                << "Cette adresse est invalide.";
        cout << "5.1.3 Bad destination mailbox address syntax" << endl;
        return EX_NOUSER;
    }

    // Le lot des destinataires est défini dans la base de données
    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");

    // Connexion à la base de données
    // FIXME : permettre un accès sans mot de passe
    db.setHostName      (settings.value("database/hostName",        "localhost"     ).toString());
    db.setPort          (settings.value("database/port",            5432            ).toInt()   );
    db.setDatabaseName  (settings.value("database/databaseName",    "laguntzaile"   ).toString());
    db.setUserName      (settings.value("database/userName",        qgetenv("USER") ).toString());
    db.setPassword      (settings.value("database/password",        qgetenv("USER") ).toString());

    if(!db.open()) {
        qCritical()
                << "Erreur d'ouverture de la connexion à la base de données :"
                << db.lastError()
                << "Veuillez vérifier le fichier de configuration"
                << settings.fileName();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    // Un retour en erreur ; débarrassons nous de ce cas spécial en premier
    if (retour) {
        // lire id_lot, id_personne et cle
        QStringList identifiant = extension.split('_');
        int id_lot = identifiant.at(0).toInt();
        int id_personne = identifiant.at(1).toInt();
        int cle = identifiant.at(2).toInt();
        // vérification standard : lot_personne avec la bonne cle, traité et reussi et sans erreur
        QSqlQuery query_lot_personne;
        if(!query_lot_personne.prepare(
                    "select *"
                    " from lot_personne"
                    " where"
                    "  id_lot = :id_lot"
                    "  and id_personne = :id_personne"
                    "  and cle = :cle"
                    "  and traite"
                    "  and reussi"
                    "  and erreur is null")) {
            qCritical()
                    << "Erreur de préparation de la requête d'identification de l'envoi :"
                    << query_lot_personne.lastError();
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_CONFIG;
        }
        query_lot_personne.bindValue(":id_lot", id_lot);
//.........这里部分代码省略.........
开发者ID:sebastiendu,项目名称:laguntzaile,代码行数:101,代码来源:main.cpp

示例9: QWidget

MQLEdit::MQLEdit(QWidget* parent, Qt::WindowFlags fl)
    : QWidget(parent, fl)
{
  setupUi(this);

  if (OpenRPT::name.isEmpty())
    OpenRPT::name = tr("MetaSQL Editor");

  _mqlSelector = 0;
  _document = _text->document();
  _document->setDefaultFont(QFont("Courier"));

  connect(_document,     SIGNAL(modificationChanged(bool)), this, SLOT(setWindowModified(bool)));
  connect(editFindAction,              SIGNAL(triggered()), this, SLOT(editFind()));
  connect(fileDatabaseConnectAction,   SIGNAL(triggered()), this, SLOT(fileDatabaseConnect()));
  connect(fileDatabaseDisconnectAction,SIGNAL(triggered()), this, SLOT(fileDatabaseDisconnect()));
  connect(fileDatabaseOpenAction,      SIGNAL(triggered()), this, SLOT(fileDatabaseOpen()));
  connect(fileDatabaseSaveAsAction,    SIGNAL(triggered()), this, SLOT(fileDatabaseSaveAs()));
  connect(fileExitAction,              SIGNAL(triggered()), this, SLOT(fileExit()));
  connect(fileNewAction,               SIGNAL(triggered()), this, SLOT(fileNew()));
  connect(fileOpenAction,              SIGNAL(triggered()), this, SLOT(fileOpen()));
  connect(filePrintAction,             SIGNAL(triggered()), this, SLOT(filePrint()));
  connect(fileSaveAction,              SIGNAL(triggered()), this, SLOT(fileSave()));
  connect(fileSaveAsAction,            SIGNAL(triggered()), this, SLOT(fileSaveAs()));
  connect(helpAboutAction,             SIGNAL(triggered()), this, SLOT(helpAbout()));
  connect(helpContentsAction,          SIGNAL(triggered()), this, SLOT(helpContents()));
  connect(helpIndexAction,             SIGNAL(triggered()), this, SLOT(helpIndex()));
  connect(searchForParametersAction,   SIGNAL(triggered()), this, SLOT(populateParameterEdit()));
  connect(toolsExecute_QueryAction,    SIGNAL(triggered()), this, SLOT(execQuery()));
  connect(toolsParse_QueryAction,      SIGNAL(triggered()), this, SLOT(parseQuery()));
  connect(viewExecuted_SQLAction,      SIGNAL(triggered()), this, SLOT(showExecutedSQL()));
  connect(viewLog_OutputAction,        SIGNAL(triggered()), this, SLOT(showLog()));
  connect(viewParameter_ListAction,    SIGNAL(triggered()), this, SLOT(showParamList()));
  connect(viewResultsAction,           SIGNAL(triggered()), this, SLOT(showResults()));

  QSqlDatabase db = QSqlDatabase().database();
  if(db.isValid() && db.isOpen())
    OpenRPT::loggedIn = true;
  else
  {
    OpenRPT::loggedIn = false;
    db = QSqlDatabase();
  }

  if (parent) // then must be embedded
  {
    if (DEBUG)
      qDebug("MQLEdit::MQLEdit(%p) OpenRPT::loggedIn = %d",
             parent, OpenRPT::loggedIn);
    fileDatabaseConnectAction->setVisible(! OpenRPT::loggedIn);
    fileDatabaseDisconnectAction->setVisible(! OpenRPT::loggedIn);

    fileExitAction->setText(tr("Close"));

    QToolBar *menuproxy = new QToolBar(this);
    menuproxy->setObjectName("menuproxy");
    menuproxy->setOrientation(Qt::Horizontal);
    verticalLayout->insertWidget(0, menuproxy);

    menuproxy->addAction(fileMenu->menuAction());
    menuproxy->addAction(editMenu->menuAction());
    menuproxy->addAction(ViewMenu->menuAction());
    menuproxy->addAction(ToolsMenu->menuAction());
    menuproxy->addAction(helpMenu->menuAction());
  }
  
  fileDatabaseConnectAction->setEnabled(!OpenRPT::loggedIn);
  fileDatabaseDisconnectAction->setEnabled(OpenRPT::loggedIn);
  fileDatabaseOpenAction->setEnabled(OpenRPT::loggedIn);
  fileDatabaseSaveAsAction->setEnabled(OpenRPT::loggedIn);
  
  _pEdit   = new ParameterEdit(this, Qt::Window);
  _log     = new LogOutput(this);
  _sql     = new LogOutput(this);
  _results = new ResultsOutput(this);

  _highlighter = new MetaSQLHighlighter(_document);

  clear();

  setDestType(MQLUnknown);
}
开发者ID:IlyaDiallo,项目名称:openrpt,代码行数:82,代码来源:mqledit.cpp

示例10: createDB

bool DatabaseManager::createDB()
{
    QSqlDatabase db = QSqlDatabase::database(DB_CONNECTION_NAME);

    // Db does not exist, or is corrupted. Open a new one and fill it.
    if (!db.open())
    {
        qDebug() << db.lastError().text();
        return false;
    }

    QFile sqlFile(":/personal-qt.sql");

    if (sqlFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QString sql = "";
        QTextStream in(&sqlFile);
        QSqlQuery qry(db);

        // qry.prepare(in.readAll());

        while (!in.atEnd())
        {
           QString line = in.readLine();

           if (line.startsWith('#'))
           {
               qDebug() << line;
           }
           else
           {
               sql += line;

               if (line.contains(';'))
               {
                   qDebug() << sql;

                   if (!qry.exec(sql))
                   {
                       qDebug() << qry.lastError().text();
                       sqlFile.close();
                       db.close();
                       return false;
                   }

                   sql = "";
               }
           }
        }

        sqlFile.close();
        db.close();

        return true;
    }
    else
    {
        db.close();
        return false;
    }
}
开发者ID:Acidburn0zzz,项目名称:personal-qt,代码行数:61,代码来源:databasemanager.cpp

示例11: cryptor

void Setup::enter() {

	QDir dir;
	dir.mkdir(QDir::homePath() + "/.booker");

	QByteArray pwOffice = this->pwOffice->text().toLatin1();
	QByteArray pwMaster = this->pwMaster->text().toLatin1();
	QByteArray pwEncryption = this->pwEncryption->text().toLatin1();

	Cryptor cryptor(pwOffice+pwOffice);

	QString dbHost = this->dbHost->text();
	QString dbDatabase = this->dbDatabase->text();
	QString dbUsername = this->dbUsername->text();
	QString dbPassword = this->dbPassword->text();

	QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL","test");
	db.setHostName(dbHost);
	db.setDatabaseName(dbDatabase);
	db.setUserName(dbUsername);
	db.setPassword(dbPassword);
	db.open();

	if(pwMasterCheck->isChecked()) {
		QSqlQuery query(db);
		QString sql = "";
		sql += "INSERT INTO connectiontest (`passwordfor`,`password`) VALUES ('master',:master);";
		query.prepare(sql);
		query.bindValue(":master",pwMaster);
		query.exec();
		query.clear();
	} else {

		QSqlQuery query(db);
		query.prepare("SELECT * FROM connectiontest WHERE passwordfor LIKE 'encryption' OR passwordfor LIKE 'master'");
		query.exec();
		while(query.next())
			if(query.value(query.record().indexOf("passwordfor")).toByteArray() == "master") pwMaster = cryptor.decrypt(query.value(query.record().indexOf("password")).toByteArray()).data();
		query.clear();

	}


	QFile cryptPwFile(QDir::homePath() + "/.booker/cryptPassword");
	if(!cryptPwFile.open(QIODevice::WriteOnly)) {
		QMessageBox::critical(this,"Failed file saving","ERROR! Can't save encryption password! Quitting...");
		this->reject();
		return;
	}
	QTextStream outPw(&cryptPwFile);
	outPw << cryptor.encrypt(pwEncryption).join("\n");
	cryptPwFile.close();


	QFile dbfile(QDir::homePath() + "/.booker/db");
	if(!dbfile.open(QIODevice::WriteOnly)) {
		QMessageBox::critical(this,"Failed file saving","ERROR! Can't save database connection details! Quitting...");
		this->reject();
		return;
	}
	QTextStream outDb(&dbfile);
	outDb << cryptor.encrypt(QString("host=%1\ndb=%2\nuname=%3\npw=%4")
				  .arg(dbHost)
				  .arg(dbDatabase)
				  .arg(dbUsername)
				  .arg(dbPassword).toLatin1()).join("\n");
	dbfile.close();


	QFile cryptCredentials(QDir::homePath() + "/.booker/officePassword");
	if(!cryptCredentials.open(QIODevice::WriteOnly)) {
		QMessageBox::critical(this,"Failed file saving","ERROR! Can't save office password! Quitting...");
		this->reject();
		return;
	}
	QTextStream outCred(&cryptCredentials);
	outCred << cryptor.encrypt(pwOffice).join("\n");
	cryptCredentials.close();

	this->accept();

}
开发者ID:ferries,项目名称:booker,代码行数:82,代码来源:setup.cpp

示例12: FCenterWindow

CenterWindow::CenterWindow(QWidget *parent) :
    FCenterWindow(parent)
{
    this->version = "3.1.0";
    QDir dir;
    QDir dir2(dir.homePath()+"/视频");
    QDir dir3(dir.homePath()+"/Videos");
    QString dbPath;
    if(dir2.exists())
    {
        dbPath = dir.homePath()+"/视频/MvGather/Database";
    }else if(dir3.exists())
    {
        dbPath = dir.homePath()+"/Videos/MvGather/Database";
    }else
    {
        dbPath = dir.homePath()+"/MvGather";
    }
    dir.mkpath(dbPath);
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//添加数据库驱动,这里用sqlite
    db.setDatabaseName(dbPath+"/MvGather.db");
    //    db.setDatabaseName("MvGather.db");
    if(db.open())
    {
        //tvId:该视频唯一编号,tvName:视频中文名.tvno_hrefs:集数与相应地址...historyNo:上次观看到的集数;quality:清晰度;tvUrl:yunfan视频列表地址;source:视频来源标识
        QSqlQuery query_creat_tb("CREATE TABLE IF NOT EXISTS playlistTB(tvId VARCHAR( 30 ) NOT NULL,tvName VARCHAR( 30 ),tvno_hrefs VARCHAR(100),historyNo VARCHAR( 30 ),quality VARCHAR( 30 ),tvUrl VARCHAR(100),source VARCHAR( 30 ))");
        query_creat_tb.exec();
        //taskId:创建下载任务的id;url任务原地址;fileSavePath:文件保存目录,percent完成的百分比
        QSqlQuery query_creat_tb2("CREATE TABLE IF NOT EXISTS dtaskTB(taskId VARCHAR(30) NOT NULL,url VARCHAR(200) NOT NULL,fileSavePath VARCHAR(200) NOT NULL,percent VARCHAR(5))");
        query_creat_tb2.exec();
    }


    playerWidget = new PlayerWidget(this);
    addWidget(tr("播放器"), tr("Player"), playerWidget);

    browseWidget = new  BrowseWidget(this);
    addWidget(tr("视频库"), tr("MvList"), browseWidget);

    recommendWidget = new RecommendWidget(this);
    addWidget(tr("推荐"), tr("MvRecomend"), recommendWidget);

    magnetWidget = new MagnetWidget(this);
    addWidget(tr("磁力链"), tr("Magnet"), magnetWidget);

    downloadManageWidget = new QScrollArea(this);
    addWidget(tr("下载"), tr("Download"), downloadManageWidget);

    downloadManageScrollAreaWidget = new QWidget(downloadManageWidget);
    downloadManageWidget->setWidget(downloadManageScrollAreaWidget);
    downloadManageScrollAreaWidgetMainLayout = new QVBoxLayout;
    downloadManageScrollAreaWidgetMainLayout->setAlignment(Qt::AlignTop);
    downloadManageScrollAreaWidget->setLayout(downloadManageScrollAreaWidgetMainLayout);

    downloadManageScrollAreaWidget->setStyleSheet("background:transparent");

    getNavgationBar()->setCurrentIndex(0);
    setAlignment(TopCenter);

    QSettings settings("MvGather", "xusongjie");
    QString preferQualitysSetting = settings.value("app/preferQualitys", "").toString();
    if(preferQualitysSetting =="")
    {
        preferQualitysSetting="高清#超清#M3U8#分段_高清_FLV#分段_高清_MP4#分段_高清_M3U8#分段_720P_FLV#分段_720P_MP4#分段_720P_M3U8#分段_1080P_FLV#分段_1080P_MP4#分段_1080P_M3U8#分段_超清_FLV#分段_超清_MP4#分段_超清_M3U8#分段_标清_FLV#分段_标清_MP4#分段_标清_M3U8#分段_高码1080P_FLV#分段_高码1080P_MP4#分段_高码1080P_M3U8#分段_原画_FLV#分段_原画_MP4#分段_原画_M3U8#分段_4K_FLV#分段_4K_MP4#分段_4K_M3U8#分段_高码4K_FLV#分段_高码4K_MP4#分段_高码4K_M3U8#分段_低清_FLV#分段_低清_MP4#分段_低清_M3U8#单段_高清_MP4#单段_高清_M3U8#单段_高清_FLV#单段_720P_FLV#单段_720P_MP4#单段_720P_M3U8#单段_1080P_FLV#单段_1080P_MP4#单段_1080P_M3U8#单段_超清_FLV#单段_超清_MP4#单段_超清_M3U8#单段_标清_FLV#单段_标清_MP4#单段_标清_M3U8#单段_高码1080P_FLV#单段_高码1080P_MP4#单段_高码1080P_M3U8#单段_原画_FLV#单段_原画_MP4#单段_原画_M3U8#单段_4K_FLV#单段_4K_MP4#单段_4K_M3U8#单段_高码4K_FLV#单段_高码4K_MP4#单段_高码4K_M3U8#单段_低清_FLV#单段_低清_MP4#单段_低清_M3U8";
        settings.setValue("app/preferQualitys",preferQualitysSetting);
    }


    connect(browseWidget,SIGNAL(play(QString)),this,SLOT(addMvToPlaylist(QString)));

    connect(playerWidget,SIGNAL(hideToFullScreen(bool)),this,SLOT(getIntofullScreenMode(bool)));
    connect(playerWidget,SIGNAL(getIntoWideModel(bool)),this,SLOT(getIntoWideModel(bool)));

    connect(magnetWidget,SIGNAL(addDownloadTask(QString)),this,SLOT(addDownloadTask(QString)));
    connect(recommendWidget,SIGNAL(addDownloadTaskSignal(QString)),this,SLOT(addDownloadTask(QString)));

    connect(getNavgationBar(),SIGNAL(indexChanged(int)),this,SLOT(firstLoadList(int)));

    hideMouseTimer = new QTimer;
    connect(hideMouseTimer,SIGNAL(timeout()),this,SLOT(hideMouse()));
    hideMouseTimer->start(500);

    loadDownloadSettings();
}
开发者ID:jun-zhang,项目名称:MvGather,代码行数:84,代码来源:centerwindow.cpp

示例13: QDialog

QgsBookmarks::QgsBookmarks( QWidget *parent, Qt::WindowFlags fl )
    : QDialog( parent, fl )
{
  setupUi( this );
  restorePosition();

  //
  // Create the zoomto and delete buttons and add them to the
  // toolbar
  //
  QPushButton *btnAdd    = new QPushButton( tr( "&Add" ) );
  QPushButton *btnDelete = new QPushButton( tr( "&Delete" ) );
  QPushButton *btnZoomTo = new QPushButton( tr( "&Zoom to" ) );
  QPushButton *btnImpExp = new QPushButton( tr( "&Share" ) );

  btnZoomTo->setDefault( true );
  buttonBox->addButton( btnAdd, QDialogButtonBox::ActionRole );
  buttonBox->addButton( btnDelete, QDialogButtonBox::ActionRole );
  buttonBox->addButton( btnZoomTo, QDialogButtonBox::ActionRole );
  buttonBox->addButton( btnImpExp, QDialogButtonBox::ActionRole );

  QMenu *share = new QMenu();
  QAction *btnExport = share->addAction( tr( "&Export" ) );
  QAction *btnImport = share->addAction( tr( "&Import" ) );
  connect( btnExport, SIGNAL( triggered() ), this, SLOT( exportToXML() ) );
  connect( btnImport, SIGNAL( triggered() ), this, SLOT( importFromXML() ) );
  btnImpExp->setMenu( share );

  connect( btnAdd, SIGNAL( clicked() ), this, SLOT( addClicked() ) );
  connect( btnDelete, SIGNAL( clicked() ), this, SLOT( deleteClicked() ) );
  connect( btnZoomTo, SIGNAL( clicked() ), this, SLOT( zoomToBookmark() ) );

  // open the database
  QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE", "bookmarks" );
  db.setDatabaseName( QgsApplication::qgisUserDbFilePath() );
  if ( !db.open() )
  {
    QMessageBox::warning( this, tr( "Error" ),
                          tr( "Unable to open bookmarks database.\nDatabase: %1\nDriver: %2\nDatabase: %3" )
                          .arg( QgsApplication::qgisUserDbFilePath() )
                          .arg( db.lastError().driverText() )
                          .arg( db.lastError().databaseText() )
                        );
    deleteLater();
    return;
  }

  QSqlTableModel *model = new QSqlTableModel( this, db );
  model->setTable( "tbl_bookmarks" );
  model->setSort( 0, Qt::AscendingOrder );
  model->setEditStrategy( QSqlTableModel::OnFieldChange );
  model->select();

  // set better headers then column names from table
  model->setHeaderData( 0, Qt::Horizontal, tr( "ID" ) );
  model->setHeaderData( 1, Qt::Horizontal, tr( "Name" ) );
  model->setHeaderData( 2, Qt::Horizontal, tr( "Project" ) );
  model->setHeaderData( 3, Qt::Horizontal, tr( "xMin" ) );
  model->setHeaderData( 4, Qt::Horizontal, tr( "yMin" ) );
  model->setHeaderData( 5, Qt::Horizontal, tr( "xMax" ) );
  model->setHeaderData( 6, Qt::Horizontal, tr( "yMax" ) );
  model->setHeaderData( 7, Qt::Horizontal, tr( "SRID" ) );

  lstBookmarks->setModel( model );

  QSettings settings;
  lstBookmarks->header()->restoreState( settings.value( "/Windows/Bookmarks/headerstate" ).toByteArray() );

#ifndef QGISDEBUG
  lstBookmarks->setColumnHidden( 0, true );
#endif
}
开发者ID:Br1ndavoine,项目名称:QGIS,代码行数:72,代码来源:qgsbookmarks.cpp

示例14: main

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    ApplicationHelper appHelper;

    QObject::connect(&app, SIGNAL(aboutToQuit()), &appHelper, SLOT(aboutToQuit()));
    signal(SIGINT, signalHandler);

    // Set application variables
    QCoreApplication::setApplicationName("pokerspiel-metaserver");
    QCoreApplication::setApplicationVersion("0.1.0");
    QCoreApplication::setOrganizationName("PokerSpielServices");
    QCoreApplication::setOrganizationDomain("pokerspielservices.me");

    // Get command line arguments
    QCommandLineParser parser;
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption serverPort(QStringList() << "P" << "port",
                                  "Port of the websocket server.",
                                  "ws_port",
                                  WEBSOCKET_PORT);
    parser.addOption(serverPort);
    QCommandLineOption mysqlHost(QStringList() << "h" << "host",
                                  "Hostname for mysql database.",
                                  "mysql_hostname",
                                  MYSQL_HOSTNAME);
    parser.addOption(mysqlHost);
    QCommandLineOption mysqlUsername(QStringList() << "u" << "username",
                                  "Username for mysql database.",
                                  "mysql_username",
                                  MYSQL_USERNAME);
    parser.addOption(mysqlUsername);
    QCommandLineOption mysqlPassword(QStringList() << "p" << "password",
                                  "Password of the mysql database.",
                                  "mysql_password",
                                  MYSQL_PASSWORD);
    parser.addOption(mysqlPassword);
    QCommandLineOption mysqlDatabase(QStringList() << "d" << "database",
                                  "Name of the mysql database.",
                                  "mysql_db",
                                  MYSQL_DB);
    parser.addOption(mysqlDatabase);

    QCommandLineOption jsonLog("json");
    jsonLog.setDescription("Output log in JSON format");
    parser.addOption(jsonLog);

    parser.process(app);

    if (parser.isSet(jsonLog)) {
        appHelper.jsonOutput = true;
        qInstallMessageHandler(jsonOutput);
    } else {
        appHelper.jsonOutput = false;
        qInstallMessageHandler(messageOutput);
    }

    // Connect to database
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName(parser.value(mysqlHost));
    db.setDatabaseName(parser.value(mysqlDatabase));
    db.setUserName(parser.value(mysqlUsername));
    db.setPassword(parser.value(mysqlPassword));
    db.setConnectOptions("MYSQL_OPT_RECONNECT=1");
    if (!db.open()) {
        qFatal("SQL Error: %s", db.lastError().text().toUtf8().constData());
    } else {
        qDebug() << "Connection to MYSQL-Server established (" << db.userName() << "@" << db.hostName() << ")";
    }

    // Start websocket server
    WebSocketServer server(parser.value(serverPort).toUInt());
    Q_UNUSED(server);

    return app.exec();
}
开发者ID:pokerspiel,项目名称:metaserver,代码行数:78,代码来源:main.cpp

示例15: data

// This gets called when the loadbackup.php script is finished
void BrowseBackup::openBackup(QNetworkReply *reply) {

	// Restore interface
	qApp->restoreOverrideCursor();
	busyLoadBackup->hide();
	date->setEnabled(true);
	search->setEnabled(true);
	list->setEnabled(true);
	load->setEnabled(true);
	closeWindow->setEnabled(true);

	// Store reply data
	QString all = reply->readAll();

	// If the reply is anything but a single 1, then something must have gone wrong
	if(all != "1") {

		QMessageBox::critical(this,"ERROR","ERROR: Unable to load backed up data!\n\nError message:\n" + all);
		return;

	}

	// We now need to get the old office pw (stored in plaintext),
	// use it to decrypt the encryption password used at that point,
	// then we re-encrypt it with the current officepw
	// and store it in a file called 'oldpwcrypt' (crypt.cpp will look there for a backup)

	// Connect to the backup database
	ConfigData data(pwOffice);
	SaverDbCred s = data.getDbLogin();
	// We now need the temporary passwords:
	QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL",QString("loadbackup%1").arg(qrand()%12345));
	db.setHostName(s.host.data());
	db.setDatabaseName(s.databaseBackup.data());
	db.setUserName(s.username.data());
	db.setPassword(s.password.data());
	db.open();

	// We need these two pw data
	QByteArray oldpwCrypt = "";
	QByteArray oldpwOffice = "";

	QSqlQuery query(db);
	query.prepare("SELECT * FROM `current` WHERE `id` NOT LIKE 'master'");
	query.exec();
	while(query.next()) {

		// Get the pws
		QString txt = query.value(query.record().indexOf("id")).toString();
		if(txt == "office")
			oldpwOffice = query.value(query.record().indexOf("txt")).toByteArray();
		else if(txt == "crypt")
			oldpwCrypt = query.value(query.record().indexOf("txt")).toByteArray();

	}
	query.clear();
	db.close();

	// We first decrypt the old encryption pw with the old pw
	Cryptor crypt(oldpwOffice, true);
	oldpwCrypt = crypt.decrypt(oldpwCrypt).data();

	// Then we re-encrypt it with the current office pw
	crypt.setPassword(pwOffice + pwOffice);
	oldpwCrypt = crypt.encrypt(oldpwCrypt).join("\n").toLatin1();

	// And we write it to the file (crypt.cpp will look there for a backup)
	QFile file(QDir::homePath() + "/.booker/oldpwcrypt");
	if(file.open(QIODevice::WriteOnly)) {
		QTextStream out(&file);
		out << oldpwCrypt;
		file.close();
	}


	// If the browser is not yet set up (first run)
	if(!browseSetup) {

		browseSetup = true;

		// Set up the heading (will hold info that it is a backup and from when)
		heading = new QLabel;
		heading->setStyleSheet("font-weight: bold; color: red; font-size: 12pt");
		// Right beside the info is a close button
		QPushButton *closeBut = new QPushButton("Close Backup");
		closeBut->setStyleSheet("font-weight: bold; font-size: 11.5pt");
		// And the header lay
		QHBoxLayout *headerLay = new QHBoxLayout;
		headerLay->addStretch();
		headerLay->addWidget(heading);
		headerLay->addSpacing(20);
		headerLay->addWidget(closeBut);
		headerLay->addStretch();

		// the two main elements
		BookingsTab *browse = new BookingsTab(pwOffice, true);
		Details *details = new Details(pwOffice, true);
		Tools *tools = new Tools(true);

//.........这里部分代码省略.........
开发者ID:ferries,项目名称:booker,代码行数:101,代码来源:browsebackup.cpp


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