Пример #1
0
void QgsMssqlNewConnection::listDatabases()
{
  testConnection( QStringLiteral( "master" ) );
  listDatabase->clear();
  QString queryStr = QStringLiteral( "SELECT name FROM master..sysdatabases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')" );

  QSqlDatabase db = QgsMssqlProvider::GetDatabase( txtService->text().trimmed(),
                    txtHost->text().trimmed(),
                    QStringLiteral( "master" ),
                    txtUsername->text().trimmed(),
                    txtPassword->text().trimmed() );
  if ( db.open() )
  {
    QSqlQuery query = QSqlQuery( db );
    query.setForwardOnly( true );
    ( void )query.exec( queryStr );

    if ( !txtService->text().isEmpty() )
    {
      listDatabase->addItem( QStringLiteral( "(from service)" ) );
    }

    if ( query.isActive() )
    {
      while ( query.next() )
      {
        QString name = query.value( 0 ).toString();
        listDatabase->addItem( name );
      }
      listDatabase->setCurrentRow( 0 );
    }
    db.close();
  }
}
Пример #2
0
FileCache::~FileCache()
{
    allocFileSpace( 0 );

    QSqlDatabase database = QSqlDatabase::database( "FileCache" );
    database.close();
}
Пример #3
0
/* checkConnectivity()
 * Called : When User Clicks Reconnect Button
 * Performs : Checks Connectivity
 */
void Settings::checkConnectivity()
{
    bool ok;
    {
        QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL","test");
        db.setDatabaseName(databasenameLE->text());
        db.setPort(portLE->text().toInt());
        db.setHostName(hostnameLE->text());
        db.setUserName(usernameLE->text());
        db.setPassword(passwordLE->text());
        ok=db.open();

        if(ok)
            QMessageBox::information(this,"DocmaQ Connection","Connection Successful. <b>" + usernameLE->text() + "</b> is now Connected to <b>" + databasenameLE->text() + "</b> Database.");
        else
            QMessageBox::critical(this,"DocmaQ Connection Error", "An Error Occured while Connecting to the Database." +
                                  tr("Please Check the Database details.\n\n") + "MySQL Reports : " + db.lastError().databaseText());
        db.close();

        settings->setValue("general/mode",ok);
        databaseRB->setChecked(ok);
        manualRB->setChecked(!ok);
    }

    QSqlDatabase::removeDatabase("test");

    f[0] = true;
}
Пример #4
0
void FrmCompras_cls::pegadados_cmp(QString x)
{
   {
	QSqlDatabase db ;		
	db = QSqlDatabase::addDatabase("QMYSQL","01");
	db.setHostName(my_hostname);
	db.setDatabaseName(my_database);
	db.setUserName(my_username);
	db.setPassword(my_password);
	bool ok = db.open();
	db = QSqlDatabase::database("01");
	
	QSqlQuery query = QSqlQuery::QSqlQuery(db);

	QString sql = "SELECT * FROM `Produtos` where proId="+x+"";
	query.exec(sql);
		//funcionou
		while (query.next()) {
			QString id = query.value(0).toString();		
			QString name = query.value(1).toString();
			QString codbarras = query.value(2).toString();
			ui_edt_idpro ->setText(id);			
			ui_edt_nomepro ->setText(name);
//			ui_edt_codbarras ->setText(codbarras);
		};
	db.close();   
   }
 QSqlDatabase::removeDatabase("01"); // correct
   
}
Пример #5
0
void SitesDatabaseInterface::deleteSite(int id)
{
    qDebug() << "db: " << this->dbPath;
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(this->dbPath);

    if(false == db.open())
    {
        qDebug() << "can not open database";
    }

    QSqlQuery query;
    query.prepare("DELETE FROM sites WHERE ID = :id;");
    query.bindValue(":id", id);
    if(false == query.exec())
    {
       qDebug() << "SQL ERROR : " << query.lastError();
    }
    db.commit();

    //We have also to delete the associated weather data to this site
    query.prepare("DELETE FROM meteo WHERE id_site = :id;");
    query.bindValue(":id", id);
    if(false == query.exec())
    {
       qDebug() << "SQL ERROR : " << query.lastError();
    }

    db.commit();
    db.close();
}
Пример #6
0
QList<Site*> SitesDatabaseInterface::getAllSites()
{
    qDebug() << "db: " << this->dbPath;
    QList<Site*> siteList;

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(this->dbPath);

    if(false == db.open())
    {
        qDebug() << "can not open database";
    }

    QSqlQuery query= db.exec("SELECT * FROM sites");
    while (query.next())
    {
        int id = query.value(0).toInt();
        QString nom = query.value(1).toString();
        QString years = query.value(2).toString();
        QStringList yearsList = years.split(";");
        Site* site = new Site();

        site->setId(id);
        site->setNom(nom);
        site->setYears(yearsList);
        siteList.append(site);
    }
    db.close();

    return siteList;
}
Пример #7
0
void initaldatabase()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL","first");
    db.setHostName("localhost");
    db.setDatabaseName("whztest");
    db.setUserName("root");
    db.setPassword("infonet313");
    if (!db.open())
    {
        cout<<"firstlink OPEN error~!"<<endl;
        exit(1);
    }
    else
    {
        qDebug()<<"Initial OK!";
        QSqlQuery query(db);
        query.exec("drop table if exists InsertTest;");
         if(!query.exec("create table if not exists InsertTest("                   
                   "id BIGINT AUTO_INCREMENT PRIMARY KEY ,"
                   "taskseq int NOT NULL,"
                   "protocoltype CHAR(10) DEFAULT 'Ethernet',"
                   "threadnumintask int NOT NULL,"
                   "idinthread int NOT NULL,"
                   "framesize int NOT NULL,"
                   "DestMac VARCHAR(60) DEFAULT NULL,"
                   "SourMac VARCHAR(60) DEFAULT NULL,"
                   "TypeorLength VARCHAR(20) DEFAULT NULL,"
                   "Data VARCHAR(6000) DEFAULT NULL,"
                   "Upperlayer VARCHAR(30) DEFAULT NULL)"))
        qDebug()<<"exec error:"<< query.lastError().databaseText();
    }
    db.close();
}
Пример #8
0
	void Database::runSqlScript(QString script_path) {
		QSqlDatabase db = QSqlDatabase::database();

		if (not db.open())
			throw new ErrorOpeningDatabase(path());

		QFile script(script_path);
		if (not script.open(QIODevice::ReadOnly | QIODevice::Text))
			throw new ErrorReadingSQLScript(script_path);

		// NOTE query object must be created after database is open
		QSqlQuery query;

		QString line;
		while (!script.atEnd()) {
			line = QString(script.readLine());
			if (lineCanBeIgnored(line))
				continue;

			if (not query.exec(line))
				throw new SqlQueryError(query);
		}
		db.close();
		script.close();
	}
Пример #9
0
// Load the DB from a DomElement
bool MemDbLoader::load(const QDomElement & elemSource, QSqlDatabase db)
{
    _lastError = "";
    
    // Login to the SQLITE memory DB

	if(db.isOpen()) {
		db.close();
		db.open();
	}

	if(db.databaseName() != memDbName) {
		_lastError = createMemoryDB();
		if(!_lastError.isEmpty()) {
			return false;
		}
		db = QSqlDatabase::database();
		if(!db.open()) {
			_lastError = "Error opening QSQLITE memory database";
			return false;
		}  
	}
	_db = db;

    QDomNodeList nlist = elemSource.childNodes();
    for(int i = 0; i < nlist.count(); i++ ) {
        QDomElement it = nlist.item(i).toElement();
        if(it.tagName()=="table") {
            parseTable(it.toElement());
        }
    }
    return _lastError.isEmpty();
}
Пример #10
0
//Creates the database for session storage
bool SessionManager::create(){
    
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("sess.db");
    
    if(db.open()){
        //Is the session table there ?
        if(db.tables().indexOf("sessions") == -1){
            QSqlQuery query(db);
            query.prepare("CREATE TABLE sessions "
                          "(id INTEGER PRIMARY KEY AUTOINCREMENT,"
                          "name TEXT,"
                          "hostname TEXT,"
                          "username TEXT,"
                          "password TEXT,"
                          "port INTEGER,"
                          "type TEXT,"
                          "initpath TEXT)");
            if(!query.exec()){
                qDebug() << query.lastInsertId();
                return false;
            }
        }
    }else{
        return false;
    }
    
    db.close();
    return true;
}
Пример #11
0
void FrmVendas_cls::on_btn_excluir_clicked()
{
QString idpro = ui_grd_vendas->item(ui_grd_vendas->currentRow (),0) ->text();
	{
		QSqlDatabase db ;		
		db = QSqlDatabase::addDatabase("QMYSQL","01");
		db.setHostName("localhost");
		db.setDatabaseName("Omega");
		db.setUserName("root");
                db.setPassword("");
		bool ok = db.open();
		db = QSqlDatabase::database("01");
		
		QSqlQuery query = QSqlQuery::QSqlQuery(db);
		
		QString sql = "delete from tmp_vendas where idpro="+idpro;
//		qDebug() << sql;
		query.exec(sql);				
		db.close();	

	    }
 
	 QSqlDatabase::removeDatabase("01"); // correct
//	qDebug() << idpro;
ui_grd_vendas->removeRow(ui_grd_vendas->currentRow ());
}
Пример #12
0
void FrmVendas_cls::pegadados_vnd(QString x)
{
   {
	QSqlDatabase db ;		
	db = QSqlDatabase::addDatabase("QMYSQL","01");
	db.setHostName("localhost");
	db.setDatabaseName("Omega");
	db.setUserName("root");
        db.setPassword("");
	bool ok = db.open();
	db = QSqlDatabase::database("01");
	
	QSqlQuery query = QSqlQuery::QSqlQuery(db);
//	QString name = ui_edt_nome -> text();
//	QString codx =x;

	QString sql = "SELECT * FROM `Produtos` where proId="+x+"";
	query.exec(sql);
		//funcionou
		while (query.next()) {
			QString id = query.value(0).toString();		
			QString name = query.value(1).toString();
			QString codbarras = query.value(2).toString();
			ui_edt_idpro ->setText(id);			
			ui_edt_nomepro ->setText(name);
//			ui_edt_codbarras ->setText(codbarras);
		};
	db.close();   
   }
 QSqlDatabase::removeDatabase("01"); // correct
      preenche_grd_vnd();
}
Пример #13
0
void tela_produto::buscar_informacoes_his_saida(int id){
    conexao_bd conexao;
    QSqlDatabase bd;

    int id_venda;
    int quantidade;
    double valor_venda_uni;
    QString data;

    std::vector< his_saidas * > aux_his;

    //realiza conexão ao banco de dados
    if (conexao.conetar_bd()){

        //Retorna o banco de dados
        bd = conexao.retorna_bd();

        //Declara a variável que irá fazer a consulta
        QSqlQuery consultar(bd);

        //realiza a consulta
        consultar.exec("SELECT l.`id_venda`, l.`quantidade`, l.`valor_venda_uni`, c.`data_venda` FROM lista_venda l,venda c WHERE l.id_venda=c.id_venda AND l.id_produto = "+QString::number(id)+";");
        while(consultar.next()){
            id_venda = consultar.value(0).toString().toInt();
            quantidade = consultar.value(1).toString().toInt();
            valor_venda_uni = consultar.value(2).toString().toDouble();
            data = consultar.value(3).toString();
            aux_his.push_back(new his_saidas(id_venda,quantidade,valor_venda_uni,data));
        }
        consultar.clear();
        bd.close();
        conexao.fechar_conexao();
    }
    mostrar_informacoes_his_saida(aux_his);
}
Пример #14
0
int main(int argc, char ** argv)
{
	QApplication app( argc, argv );
	QCoreApplication::setApplicationName("qrdc");
	QCoreApplication::setApplicationVersion("0.0.1");
	QCoreApplication::setOrganizationName("TI_Eugene");
	QCoreApplication::setOrganizationDomain("eap.su");
	// <tr>
	QTranslator appTranslator;
	QString trpath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);	// /usr/share/qt4/translations
	QString trfile = QCoreApplication::applicationName() + "_" + QLocale::system().name().left(2);
	if (not QFile::exists(trpath + QDir::separator() + trfile + ".qm"))
		trpath = app.applicationDirPath() + QDir::separator() + "i18n";
	appTranslator.load(trpath + QDir::separator() + trfile);
	app.installTranslator(&appTranslator);
	// </tr>
	// <db>
	QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
	if (!createConnection(db))
		return 1;
	// </db>
	MainWindowImpl *win = new MainWindowImpl();
	win->setModels(&db);
	win->go(); 
	app.connect( &app, SIGNAL( lastWindowClosed() ), &app, SLOT( quit() ) );
	int retvalue = app.exec();
	delete win;
	db.close();
	return retvalue;
}
Пример #15
0
DataConnect::DataConnect()
{
        QSqlDatabase mydb = QSqlDatabase::addDatabase("QSQLITE");
        mydb.setDatabaseName("data.db");
        if  (mydb.open()) {
            std::cout<<"Database is open\n";
        } else {
            std::cout<<"Database is not open\n";
        }
        QSqlQuery comman;
        QString exc = "create table if not exists collection ( id INTEGER NOT NULL , type VARCHAR(100), dataType VARCHAR(100),title VARCHAR(100),version VARCHAR(100),publisher VARCHAR(100), yearRecored int, duration int, category VARCHAR(100) );";
        if (comman.exec(exc)) {
            std::cout << "collection data run\n";
        } else {
            std::cout << "collection data not run\n";
        }
        exc = "create table if not exists items ( id INTEGER NOT NULL, idenCode int,barcode int,borrowStatus VARCHAR(100),borrTime int,dateBorr VARCHAR(100), dayBorr int );";

        if (comman.exec(exc)) {
            std::cout << "items data run\n";
        } else {
            std::cout << "item data not run\n";
        }

        exc = "create table if not exists borrowers ( id INTEGER NOT NULL,name VARCHAR(100),type VARCHAR(100),department VARCHAR(100),mobileNumber VARCHAR(100), itemBorr int, itemLate int , itemString VARCHAR(100));";

        if (comman.exec(exc)) {
            std::cout << "borrowers data run\n";
        } else {
            std::cout << "borrowers data not run\n";
        }
        mydb.close();
}
Пример #16
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow fenetre;

    TacheManager* tm = TacheManager::getInstance();
    ProjetManager* pm = ProjetManager::getInstance();
    EvenementManager* em = EvenementManager::getInstance();

    // Creates directory if non existent
    QDir directory(QDir::homePath()+QDir::separator()+".projectCalendar");
    directory.mkdir(directory.path());

    // Connect to DB
    QSqlDatabase sdb = QSqlDatabase::addDatabase("QSQLITE");
    sdb.setDatabaseName(directory.absolutePath()+QDir::separator()+"projets_taches.sqlite");

    if (sdb.open()) {
        QSqlQuery query1(sdb);
        bool res1 = query1.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='PROJETS'");

        QSqlQuery query2(sdb);
        bool res2 = query2.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='TACHES'");

        QSqlQuery query3(sdb);
        bool res3 = query3.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='EVENEMENTS'");

        QSqlQuery query4(sdb);
        bool res4 = query4.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='TACHES_PRECEDENTES'");

        if (!res1 || !res2 || !res3 || !res4 ||
                !query1.next() || !query2.next() || !query3.next() || !query4.next()) {
            query1.clear();
            query2.clear();
            qDebug()<<"Invalid DB. Creating new one...";
            fenetre.showError("Project Calendar", "La base de donnée locale actuelle est vide ou invalide. Elle va être recréée. Vous êtes susceptible de perdre des données.");
            QFile sql_ldd(":/assets/TABLES.sql");
            if (!sql_ldd.open(QIODevice::ReadOnly | QIODevice::Text)) {
                fenetre.showError("Project Calendar", "Erreur lors de la lecture de TABLES.sql");
                sdb.close();
                app.exit(0);
                return 0;
            }
            QTextStream in(&sql_ldd);
            QString sql = in.readAll();
            QStringList sqlStatements = sql.split(';', QString::SkipEmptyParts);
            int successCount = 0;

            foreach(const QString& statement, sqlStatements) {
                if (statement.trimmed() != "") {
                    QSqlQuery query(sdb);
                    if (query.exec(statement))
                        successCount++;
                    else
                        qDebug() << "Failed:" << statement << "\nReason:" << query.lastError();
                }
            }
            qDebug()<<"Successfully";
        }
Пример #17
0
void QSqlDatabaseProto::close()
{
  QSqlDatabase *item = qscriptvalue_cast<QSqlDatabase*>(thisObject());
  if (item)
    item->close();
  else if (! thisObject().isNull())
    thisObject().toVariant().value<QSqlDatabase>().close();
}
Пример #18
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE","file.db");
    db.setDatabaseName(QDir::homePath()+"/.rationality/file.db");

    if(!db.open())
           qWarning()<<"Errore di connessione";
    QSqlQuery myQuery = QSqlQuery(db);

  /*  if (myQuery.exec("CREATE TABLE tag (key INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL);")) qWarning()<<"Tabella creata";
//    else qWarning()<<"Errore o tabella esistente";
    if (myQuery.exec("CREATE TABLE parent (child INTEGER NOT NULL, parent INTEGER NOT NULL);")) qWarning()<<"Tabella creata";
//    else qWarning()<<"Errore o tabella esistente";
    if (myQuery.exec("CREATE TABLE filetag(file INTEGER NOT NULL, tag INTEGER NOT NULL);")) qWarning()<<"Tabella creata";
//    else qWarning()<<"Errore o tabella esistente";
    if (myQuery.exec("CREATE TABLE file (key INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL,  path TEXT NOT NULL);")) qWarning()<<"Tabella creata";
  //  else qWarning()<<"Errore o tabella esistente";
  //   myQuery.exec("INSERT INTO tag VALUES (-1,'Root');");*/
    if (myQuery.exec("CREATE TABLE tag (key INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,parent INTEGER NOT NULL, name TEXT NOT NULL, hidden INTEGER NOT NULL);")) qWarning()<<"Tabella creata";
    if (myQuery.exec("CREATE TABLE filetag(file INTEGER NOT NULL, tag INTEGER NOT NULL);")) qWarning()<<"Tabella creata";
    if (myQuery.exec("CREATE TABLE file (key INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL,  path TEXT NOT NULL, rating INTEGER, CONSTRAINT rating_min_5 CHECK rating < 5 );")) qWarning()<<"Tabella creata";


   if (myQuery.exec("SELECT tag.name FROM tag;")) {
        QString t;
        while (myQuery.next()){
            t=myQuery.value(0).toString();
            qWarning()<<t;
        }
    }
    if (myQuery.exec("SELECT file.name FROM file;")) {
        QString t;
        while (myQuery.next()){
            t=myQuery.value(0).toString();
            qWarning()<<t;
        }
     }





     QString cmd="";
     char c[200];
     while (1) {
         cout << "cmd: ";
         cin.getline(c,200);
         cmd = QString::fromStdString(c);
         if (QString::compare(cmd,"exit")==0) break;
         if (myQuery.exec(cmd)) cout << "\n";
         else cout << "Comando non eseguito\n";

     }
    db.close();

    return 0;
}
Пример #19
0
void ConstellationArtComponent::loadData(){
    if(m_ConstList.isEmpty()) {
        QSqlDatabase skydb = QSqlDatabase::addDatabase("QSQLITE", "skycultures");
        #ifdef Q_OS_OSX
        QString dbfile = KSPaths::locate(QStandardPaths::GenericDataLocation, "/skycultures/skycultures.sqlite");
        #else
        QString dbfile = KSPaths::locate(QStandardPaths::GenericDataLocation, "skycultures.sqlite");
        #endif

        skydb.setDatabaseName(dbfile);
        if (skydb.open() == false)
        {
            qWarning() << "Unable to open sky cultures database file " << dbfile << endl;
            return;
        }
        QSqlQuery get_query(skydb);

        if(cultureName=="Western")
        {
            if (!get_query.exec("SELECT * FROM western"))
            {
                qDebug() << get_query.lastError();
                return;
            }
        }
        if(cultureName=="Inuit")
        {
            if (!get_query.exec("SELECT * FROM inuit"))
            {
                qDebug() << get_query.lastError();
                return;
            }
        }

        while (get_query.next())
        {
            QString abbreviation   = get_query.value("Abbreviation").toString();
            QString filename       = get_query.value("Filename").toString();
            QString midpointRA            = get_query.value("MidpointRA").toString();
            QString midpointDEC           = get_query.value("MidpointDEC").toString();
            double pa                 = get_query.value("Position Angle").toDouble();
            double w         = get_query.value("Width").toDouble();
            double h         = get_query.value("Height").toDouble();

            dms midpointra = dms::fromString(midpointRA,false);
            dms midpointdec = dms::fromString(midpointDEC,true);

            // appends constellation info
            ConstellationsArt *ca = new ConstellationsArt(midpointra, midpointdec, pa, w,h, abbreviation, filename);
            m_ConstList.append(ca);
            //qDebug()<<"Successsfully read skyculture.sqlite"<<abbreviation<<filename<<midpointRA<<midpointDEC<<pa<<w<<h;
            records++;
        }
        //qDebug()<<"Successfully processed"<<records<<"records for"<<cultureName<<"sky culture";
        skydb.close();
    }
}
Пример #20
0
void DataManager::saveDump(QString dbname, QString tableName, vector < QString > &keyNames, vector < QString > &typeNames, vector < vector < T > > &X){

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbname);
    db.open();
    QSqlQuery query(db);
    QString statement;

    int rows = X.size();
    int rowsLeft = X.size();
    int rowsUsed = 0;

    Q_ASSERT(X[0].size() == keyNames.size());

    // Delete the existing table
    statement = "DROP TABLE " + tableName + ";";
    query.exec(statement);

    // Build the new table
    statement = "CREATE TABLE " + tableName;
    statement = statement + "(" + keyNames[0] + " " + typeNames[0];
    for(int i=1; i < keyNames.size(); i++){
        statement = statement + ", " + keyNames[i] + " " + typeNames[i];
    }
    statement = statement + ");";

    query.exec(statement);

    statement = "INSERT INTO " + tableName + " VALUES";
    for(int i=0; i < X.size(); i++){

        statement = statement + " (" + QString::number(X[i][0]);
        for(int j=1; j < X[i].size(); j++){

            statement = statement + ", " + QString::number(X[i][j]);
        }

        rowsUsed++;
        if(rowsUsed%400 == 0){

            statement = statement + ");";
            query.exec(statement);
            statement = "INSERT INTO " + tableName + " VALUES";
            rowsLeft = rowsLeft - 400;
            emit saveTick(400);

        }else if(rowsUsed < rows){
            statement = statement + "),";
        }else{
            statement = statement + ");";
        }
    }
    query.exec(statement);
    emit saveTick(rowsLeft);

    db.close();
}
Пример #21
0
Database::Database() {
  QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
  db.setDatabaseName(PKGDATADIR "/data/database.db3");
  if(db.open()) {
    loadTableWithName("A", db);
    loadTableWithName("AA", db);
    loadTableWithName("B", db);
    loadTableWithName("BH", db);
    loadTableWithName("C", db);
    loadTableWithName("CH", db);
    loadTableWithName("D", db);
    loadTableWithName("Dd", db);
    loadTableWithName("Ddh", db);
    loadTableWithName("Dh", db);
    loadTableWithName("E", db);
    loadTableWithName("G", db);
    loadTableWithName("Gh", db);
    loadTableWithName("H", db);
    loadTableWithName("I", db);
    loadTableWithName("II", db);
    loadTableWithName("J", db);
    loadTableWithName("JH", db);
    loadTableWithName("K", db);
    loadTableWithName("KH", db);
    loadTableWithName("Khandatta", db);
    loadTableWithName("L", db);
    loadTableWithName("M", db);
    loadTableWithName("N", db);
    loadTableWithName("NGA", db);
    loadTableWithName("NN", db);
    loadTableWithName("NYA", db);
    loadTableWithName("O", db);
    loadTableWithName("OI", db);
    loadTableWithName("OU", db);
    loadTableWithName("P", db);
    loadTableWithName("PH", db);
    loadTableWithName("R", db);
    loadTableWithName("RR", db);
    loadTableWithName("RRH", db);
    loadTableWithName("RRI", db);
    loadTableWithName("S", db);
    loadTableWithName("SH", db);
    loadTableWithName("SS", db);
    loadTableWithName("T", db);
    loadTableWithName("TH", db);
    loadTableWithName("TT", db);
    loadTableWithName("TTH", db);
    loadTableWithName("U", db);
    loadTableWithName("UU", db);
    loadTableWithName("Y", db);
    loadTableWithName("Z", db);

    loadSuffixTableFromDatabase(db);

    db.close();
  }
}
Пример #22
0
void SQLManager::reopenConnection (const QString& name)
{
  emit connectionAboutToBeClosed(name);

  QSqlDatabase db = QSqlDatabase::database(name);

  db.close();
  isValidAndOpen(name);
}
Пример #23
0
bool add_depend(QString filename , int revision_number)
{

    QDir dir(data_path); // set the path to application data dir
    dir.cd("WTL_appdata"); //  change the directory to application data dir

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//not dbConnection
    db.setDatabaseName(dir.absoluteFilePath("WTL.db"));
    if(!db.open())
    {
        qDebug() <<"error in opening DB";
    }
    else
    {
        qDebug() <<"connected to DB" ;
    }

    QSqlQuery query;

    query.prepare("INSERT INTO Dependencies (depe_fileName,revision_number) "
                  "VALUES (:depe_filename , :revision_number )");



    query.bindValue(":depe_filename",filename);
    query.bindValue(":revision_number", revision_number);



    if(query.exec())
    {
        qDebug() << "done";
        db.close(); //  dependencies are added now
        return(true);
    }
    else
    {
        qDebug() << query.lastError();
        db.close();

    }
    return (false);

}
Пример #24
0
void new_db::on_okay() {
	QMessageBox* db_messages = new QMessageBox();
	bool success = true;
	QDir dir;
	QString db_dir = dir_line->text();
	QString db_name = db_name_line->text();
	if(!QFile(db_dir).exists()) {
		dir.mkpath(db_dir);
	}
	QString db_check = db_name.right(3);
	if (QString::compare(db_check, ".db", Qt::CaseInsensitive) != 0) {
		db_name = db_name + ".db";
	}
	QString db_path = db_dir + "/" + db_name;
	if(!QFile(db_path).exists()){

		QString email = email_line->text();
		QString pass =  pass_line->text();
		QSqlDatabase* db = new QSqlDatabase();

		*db = QSqlDatabase::addDatabase("QSQLITE");

		db->setDatabaseName(db_path);
		if(db->open()){
			QSqlQuery query;
			query.prepare("create table user(email text, pass text)");
			success = exec_query(query, db_messages, success);
			query.prepare("insert into user values( '" + email + "', '" + pass + "' )");
			success = exec_query(query, db_messages, success);
			db->close();
			if (success == true){
				db_messages->setText("Database was succesfully created.");
				db_messages->exec();
			 /*
				manage_db* asitor_main = new manage_db();
				asitor_main->show();
				this->hide();	
			 */
			}
		}else{
			db_messages->setText("Error occured while creating new database file.");
			db_messages->exec();
		}
	}else{
		QFileInfo* db_path_info = new QFileInfo(db_path);
		if (db_path_info->isDir()) {
			db_messages->setText("Error: A directory already exists with name of the database file specified.");
			db_messages->exec();
		}else{
			db_messages->setText("Error: A file already exists with name of the database file specified.");
			db_messages->exec();
		}
	}
	
	
}
Пример #25
0
void TableWindow::ChangePassword()
{
    ChangePasswordWindow *changePasswordWindow = new ChangePasswordWindow(0, login);
    changePasswordWindow->show();

    Database database = Database::getInstance();
    QSqlDatabase db = database.getDatabase();
    db.close();
    close();
}
ManageLibraryDialog::~ManageLibraryDialog()
{
    delete ui;
    {
        QSqlDatabase db = QSqlDatabase::database(manageLibConn);
        if (db.isOpen())
            db.close();
    }
    QSqlDatabase::removeDatabase(manageLibConn);
}
Пример #27
0
void MQLEdit::fileDatabaseDisconnect()
{
  QSqlDatabase db = QSqlDatabase::database();
  if(db.isValid())
    db.close();

  OpenRPT::loggedIn = false;
  fileDatabaseConnectAction->setEnabled(!OpenRPT::loggedIn);
  fileDatabaseDisconnectAction->setEnabled(OpenRPT::loggedIn);
}
void ConexaoBanco::FecharBanco()
{
    QStringList conexoes = db.connectionNames();

    for( int i = 0; i < conexoes.size() ; ++i )
    {
        db.close();
        db.removeDatabase( conexoes.at( i ) );
    }
}
Пример #29
0
bool createDB(const QString &path) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(path);
    if (!db.open()) {
        return false;
    }
    bool r;
    QSqlQuery query(db);
    r = query.exec("create table `fx_user` ("
        "`id` integer primary key,"
        "`name` varchar(32) not null unique,"
        "`email` varchar(32),"
        "`true_name` varchar(16),"
        "`department` integer not null,"
        "`icon` text,"
        "`status` int(1) not null default 1,"
        "`gmt_create` datetime not null,"
        "`gmt_modify` datetime not null"
        ");");if (!r)return r;
    r = query.exec("create table `fx_department` ("
        "`id` integer primary key,"
        "`parent_id` integer not null default 0,"
        "`name` varchar(32) not null,"
        "`gmt_create` datetime not null,"
        "`gmt_modify` datetime not null"
        ");");if (!r)return r;
    r = query.exec("create table `fx_chatlog` ("
        "`id` integer primary key,"
        "`sourceid` integer not null,"
        "`targetid` integer not null,"
        "`type` int(1) not null,"
        "`msg` text,"
        "`gmt_create` datetime not null"
        ");");if (!r)return r;
    r = query.exec("create table `fx_recent_contact` ("
        "`userid` integer not null,"
        "`contactid` integer not null,"
        "`last_time` datetime not null,"
        "constraint pk_recent primary key (userid, contactid)"
        ");");if (!r)return r;

    r = query.exec("create table `status` ("
        "`key` varchar(64) not null primary key,"
        "`value` varchar(255) not null default ''"
        ");");if (!r) return r;

    r = query.exec("insert into `status` values"
        "('last_user_update_time', ''),"
        "('last_department_update_time', ''),"
        "('last_user_name', '');");if (!r) return r;

    db.close();
    QSqlDatabase::removeDatabase(db.connectionName());
    return true;
}
Пример #30
0
/* ----------------------------------------------------------------------------------
 * Переопределенный метод базового класса.
 */
bool DbAuthn::eventFilter( QObject * watched, QEvent * event )
{
    if(event->type()==QEvent::MouseButtonPress  &&  watched==m_pCbDataBaseName)
    {
        /* Открытие выпадающего списка. Сформировать список баз данных, доступных
         * для выбора.
         */
        QString currentSelection = m_pCbDataBaseName->currentText();
        m_pCbDataBaseName->clear();

        static const char connectionName[] = "DBAUTHN_CB";
        {
            QSqlDatabase db = QSqlDatabase::addDatabase(QString("QMYSQL"), QString(connectionName));
            db.setHostName( m_pLeHost->text() );
            db.setUserName( m_pLeUserName->text() );
            db.setPassword( m_pLeUserPassword->text() );
            db.setPort( m_pLePort->text().toInt() );
            db.setDatabaseName("");

            if(db.open() == true)
            {
                QSqlQuery query( db );
                query.setForwardOnly( true );
                if( query.exec( QString("SHOW DATABASES;") ) == true )
                {
                    while (query.next() == true)
                    {
                        QString databaseName = query.value(0).toString();
                        if(databaseName.isEmpty() == false)
                            m_pCbDataBaseName->addItem( databaseName );
                    } // while (query.next() == true)
                    query.finish();
                    query.clear();
                } // if( query.exec( sql ) == true )
                else
                {
                    showSqlError( query.lastError().text() );
                }
            } // if(db.open() == true)
            else
            {
                showSqlError( db.lastError().text() );
            }

            if(db.isOpen() == true)
                db.close();
        }
        QSqlDatabase::removeDatabase( QString(connectionName) );

        int newIndex = m_pCbDataBaseName->findText(currentSelection, static_cast<Qt::MatchFlags>( Qt::MatchFixedString ));
        if(newIndex >= 0)
            m_pCbDataBaseName->setCurrentIndex( newIndex );
    }
    return QDialog::eventFilter(watched, event);
}