Exemplo n.º 1
0
void query1(int now,int w,int h)
{
	int th;
	if(now==4)
	{
		th=h>b[now]?h:b[now];
		if((w+a[now])*th<max)
		{
			max=(w+a[now])*th;
			cur=0;
			p[cur++]=(w+a[now])>th?th:(w+a[now]);
		}
		else if((w+a[now])*th==max)
		{
			p[cur++]=(w+a[now])>th?th:(w+a[now]);
		}
		th=h>a[now]?h:a[now];
		if((w+b[now])*th<max)
		{
			max=(w+b[now])*th;
			cur=0;
			p[cur++]=(w+b[now])>th?th:(w+b[now]);
		}
		else if((w+b[now])*th==max)
		{
			p[cur++]=(w+b[now])>th?th:(w+b[now]);
		}
	}
	else
	{
		query1(now+1,w+a[now],b[now]>h?b[now]:h);
		query1(now+1,w+b[now],a[now]>h?a[now]:h);
	}
}
Exemplo n.º 2
0
 int query1(int ul,int ur,int rt){
     if(ul<=e[rt].l&&ur>=e[rt].r){
         if(e[rt].rflag) return e[rt].rflag;
         else return -1;
     }
     int mid=(e[rt].l+e[rt].r)>>1;
     if(ur<=mid) return query1(ul,ur,lson);
     else if(ul>mid) return query1(ul,ur,rson);
     else {
         int t1=query1(ul,ur,lson);
         int t2=query1(ul,ur,rson);
         if(t2!=-1) return t2;
         return t1;
     }
 }
Exemplo n.º 3
0
bool CreateLog::checkIfRoomNotVacant(QString room_ids)
{
    DbMysql* d = DbMysql::getInstance();
    QMessageBox msgBox;
    if(!d->getConnection().open())
    {
        msgBox.critical(this,"Error","Failed to connect database.1");
        return false;
    }
    else
    {
        QSqlQuery query1( "select * from rooms where room_id in ("+room_ids+") and room_state=1;" ,d->getConnection());
        if(!query1.isActive())
        {
            msgBox.critical(this,"Error","Failed to connect database.");
        }
        else
        {
            if(query1.size() > 0)
            {
                return false;
            }
            else return true;
        }
    }
}
Exemplo n.º 4
0
Serversetform::Serversetform(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Serversetform)
{
    ui->setupUi(this);
    litedb = QSqlDatabase::database("localdb");
    QSqlQuery query1(litedb);
    query1.exec("select * from systemset;");
    query1.next();

    QString setip = query1.value("remoteserverip").toString();
    ui->remoteserverip->setText(setip);
    QString setport = query1.value("remoteserverport").toString();
    ui->remoteserverport->setText(setport);
    QString remotedbname = query1.value("remoteserverdbname").toString();
    ui->remotedbname->setText(remotedbname);
    QString remoteusername = query1.value("remoteserverusername").toString();
    ui->remoteserverusername->setText(remoteusername);
    QString remoteuserpassword = query1.value("remoteserveruserpassword").toString();
    ui->remoteserveruserpassword->setText(remoteuserpassword);
    disconnect(ui->DBtypecombo,SIGNAL(currentIndexChanged(QString)),this,SLOT(on_DBtypecombo_currentIndexChanged(QString)));
    ui->DBtypecombo->addItem("MYSQL");
    ui->DBtypecombo->addItem("ODBC");
    QString remoteservertype = query1.value("remoteservertype").toString();
    ui->DBtypecombo->setCurrentText(remoteservertype);
    connect(ui->DBtypecombo,SIGNAL(currentIndexChanged(QString)),this,SLOT(on_DBtypecombo_currentIndexChanged(QString)));

}
void MainWindow::readDb()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
  /*  db.setHostName("localhost");
    db.setDatabaseName("technolo");
    db.setUserName("root");
    db.setPassword("");
*/

 db.setDatabaseName(QDir::current().absoluteFilePath("technologybasic.db"));
        db.open();
        QSqlQuery query1("SELECT * from jos_content order by title;");
        QSqlRecord record = query1.record();
        while (query1.next())
        {
            TitleVar << query1.value(record.indexOf("title")).toString();
            TextVar << query1.value(record.indexOf("introtext")).toString();
        }
        QSqlQuery query2("SELECT * from jos_categories");
        QSqlRecord record1 = query2.record();
        while (query2.next())
        {
           CatVar << query2.value(record1.indexOf("catalias")).toString();
        }

}
Exemplo n.º 6
0
bool CreateBooking::checkBookingAvail(QString date_from, QString date_to, int room_id)
{
    DbMysql* d = DbMysql::getInstance();
    QMessageBox msgBox;

    if(!d->getConnection().open())
    {
        //msgBox.critical(this,"Error","Failed to connect database.1");
        return false;
    }
    else
    {
        QSqlQuery query1("SELECT * FROM `room_bookings` where room_id="+QString::number(room_id)+" and (( booking_from>='"+date_from+"' and booking_to <= '"+date_to+"') or (booking_from>='"+date_from+"' and booking_from <= '"+date_to+"') or (booking_to>='"+date_from+"' and booking_to <= '"+date_to+"'));",d->getConnection());
        qDebug()<<query1.lastQuery();

        if(query1.isActive())
        {
            if(query1.size() > 0)
            {
                return false;
            }
            else return true;
        }
        else return false;
    }

}
Exemplo n.º 7
0
void MainWindow::refresh_full_calls()
{
    QSqlQuery query(db2);
    query.exec("CREATE TEMPORARY TABLE `tmp_phonebook_2` (`phoneno` varchar(50) NOT NULL,`cusname` varchar(50) NOT NULL DEFAULT '') ENGINE=MEMORY DEFAULT CHARSET=utf8;");
    query.exec("CREATE TEMPORARY TABLE `tmp_phonebook_3` (`phoneno` varchar(50) NOT NULL,`cusname` varchar(50) NOT NULL DEFAULT '') ENGINE=MEMORY DEFAULT CHARSET=utf8;");
    QSqlQuery query1(db1);
    query1.exec("select p.phoneno,c.name from phonebook p, customers c where c.id=p.cusid");
    while(query1.next())
    {
        query.exec("insert into tmp_phonebook_2 (phoneno,cusname) values('"+query1.value(0).toString()+"','"+query1.value(1).toString()+"')");
        query.exec("insert into tmp_phonebook_3 (phoneno,cusname) values('"+query1.value(0).toString()+"','"+query1.value(1).toString()+"')");

    }


    //query.exec("select t.id,c.name as "+trUtf8("ΠΕΛΑΤΗΣ")+",p.description as "+trUtf8("ΤΟΠΟΣ")+",s.description as "+trUtf8("PROJECT")+",TIMESTAMPDIFF(MINUTE,t.start_time,t.end_time) as "+trUtf8("ΔΙΑΡΚΕΙΑ")+",t.start_time as "+trUtf8("ΕΝΑΡΞΗ")+",t.end_time as "+trUtf8("ΛΗΞΗ")+",t.price as "+trUtf8("ΧΑΩ")+",t.comment as "+trUtf8("ΣΧΟΛΙΑ")+" from tasks t left outer join subprojects s on t.projectid=s.id left outer join places p on t.placeid=p.id,customers c where t.cusid=c.id order by t.start_time");

    query.exec("select date_format(c.calldate,'%d/%m/%y %H:%i') as '"+trUtf8("ΩΡΑ ΚΛΗΣΗΣ")+"',c.src as '"+trUtf8("ΚΑΛΩΝ")+"',c.dst as '"+trUtf8("ΚΑΛΟΥΜΕΝΟΣ")+"',c.duration as '"+trUtf8("ΔΙΑΡΚΕΙΑ")+"',concat(ifnull((select cusname from tmp_phonebook_2 where phoneno=c.src),''),ifnull((select cusname from tmp_phonebook_3 where phoneno=substring(c.dst,2,15)),'')) as '"+trUtf8("ΠΕΛΑΤΗΣ")+"' from cdr c where c.dstchannel like '"+g_ASTERISK_EXTENSION+"%' or c.channel like '"+g_ASTERISK_EXTENSION+"%'order by c.calldate");

    //        query.exec("select t.id,c.name as "+trUtf8("ΠΕΛΑΤΗΣ")+",p.description as "+trUtf8("ΤΟΠΟΣ")+",s.description as "+trUtf8("PROJECT")+",TIMESTAMPDIFF(MINUTE,t.start_time,t.end_time) as "+trUtf8("ΔΙΑΡΚΕΙΑ")+",date_format(t.start_time,'%d/%m/%Y %h:%i') as "+trUtf8("ΕΝΑΡΞΗ")+",date_format(t.end_time,'%d/%m/%Y %h:%i') as "+trUtf8("ΛΗΞΗ")+",t.price as "+trUtf8("ΧΑΩ")+",t.comment as "+trUtf8("ΣΧΟΛΙΑ")+" from tasks t left outer join subprojects s on t.projectid=s.id left outer join places p on t.placeid=p.id,customers c where t.cusid=c.id and date(start_time)=current_date order by t.start_time");
    if(query.size()>0)
    {
        full_calls_model->setQuery(query);
        ui->tableAllCalls->setModel(full_calls_model);
        ui->tableAllCalls->resizeColumnToContents(0);
        ui->tableAllCalls->resizeColumnToContents(1);
        ui->tableAllCalls->resizeColumnToContents(2);
        ui->tableAllCalls->resizeColumnToContents(3);
        ui->tableAllCalls->setAlternatingRowColors(true);
        ui->tableAllCalls->scrollToBottom();
    }
    query.exec("drop temporary table tmp_phonebook_2");
    query.exec("drop temporary table tmp_phonebook_3");

}
Exemplo n.º 8
0
/*!
 * L&ouml;scht die Tabellen.
 */
void Datenbank::clean()
{
	QSqlQuery query1("DROP TABLE h_daten;");
	query1.exec();
	QSqlQuery query2("DROP TABLE h_schueler;");
	query2.exec();
}
Exemplo n.º 9
0
void vnc::on_pushButton_3_clicked()
{
    Save=0;
    QString ip, Cantidad;
    ip=ui->lineEdit_3->text();
    if (ip == "")
    {
        QMessageBox m; if (Stilo == "A") m.setStyleSheet("background-color: "+cantidad51+"; color: "+cantidad50+"; font-size: "+cantidad49+"pt; font-style: "+DatoTalla+"; font-family: "+cantidad47+"; font-weight: "+DatoNegro+"");
        m.setText(tr("No hay datos para insertar."));
        m.exec();
        return;
    }
    QSqlQuery query(db);
    query.exec("SELECT ip FROM ipVnc WHERE ip='"+ip+"'");
    query.first();
    if (query.isSelect())
        Cantidad=query.value(0).toString();
    if (ip == Cantidad)
    {
        QMessageBox m; if (Stilo == "A") m.setStyleSheet("background-color: "+cantidad51+"; color: "+cantidad50+"; font-size: "+cantidad49+"pt; font-style: "+DatoTalla+"; font-family: "+cantidad47+"; font-weight: "+DatoNegro+"");
        m.setText(tr("Ya esta introducida esta ip en la base de datos."));
        m.exec();
        return;
    }

    QSqlQuery query1(db);
    query1.prepare("INSERT INTO ipVnc (ip)"
                  "VALUES (:ip)");
    query1.bindValue(":ip", ip);
    query1.exec();
    Model1->select();
    ui->tableView->setModel(Model1);
    ui->lineEdit_3->setText("");
}
Exemplo n.º 10
0
void ZhscWidget::buildTEPoet()
{
  if ( bConStatus )
  {
    QString sq1 = "select content from poet where dynastyno = '" + smDynasty[nDynasty] + "' and poetno = '" + smPoet[nPoet] + "'";
    QSqlQuery query1( sq1 );
    
    tePoet->setText( "" );

    if ( query1.size() > 0 )
    {
      if ( query1.next() )
      {
        tePoet->setText( trUtf8( query1.value(0).toByteArray() ) );
      }
    }
    else
    {
      QString sq2 = "select content from poet where dynastyno = 'O' and poetno = '0023'";
      QSqlQuery query2( sq2 );

      if ( query2.size() > 0 )
      {
        if ( query2.next() )
        {
          tePoet->setText( trUtf8( query2.value(0).toByteArray() ).replace( 11, 2, cbPoet->currentText() ) );
        }
      }
    }
  }
}
Exemplo n.º 11
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // 创建数据库连接
    if (!createConnection()) return 1;

    // 使用QSqlQuery查询连接1的整张表,先要使用连接名获取该连接
    QSqlDatabase db1 = QSqlDatabase::database("connection1");
    QSqlQuery query1(db1);
    qDebug() << "connection1:";
    query1.exec("select * from student");
    while(query1.next())
    {
        qDebug() << query1.value(0).toInt() << query1.value(1).toString();
    }
     // 使用QSqlQuery查询连接2的整张表
    QSqlDatabase db2 = QSqlDatabase::database("connection2");
    QSqlQuery query2(db2);
    qDebug() << "connection2:";
    query2.exec("select * from student");
    while(query2.next())
    {
        qDebug() << query2.value(0).toInt() << query2.value(1).toString();
    }

    return a.exec();
}
Exemplo n.º 12
0
void FormGestioneFerie::on_cbMatricola_currentIndexChanged(const QString &arg1)
{

    ui->cbCognome->setCurrentIndex(ui->cbMatricola->currentIndex());
    QSqlQuery query1(QString("SELECT nome FROM anagrafica where Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));
    query1.next();
    ui->lNome->setText( query1.value(0).toString() );

    QSqlTableModel *model = new QSqlTableModel(this, this->db);
    model->setTable("assenze");
    model->setEditStrategy(QSqlTableModel::OnFieldChange);
    model->select();
    model->setFilter(QString("Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));

    model->sort(2,Qt::AscendingOrder);
      model->setHeaderData(1, Qt::Horizontal, tr("MATRICOLA"));
      model->setHeaderData(2, Qt::Horizontal, tr("DATA"));
      model->setHeaderData(3, Qt::Horizontal, tr("CAUSA"));
      ui->tvPermessi->setModel(model);
      ui->tvPermessi->hideColumn(0);
      ui->tvPermessi->resizeColumnsToContents();
      ui->tvPermessi->resizeRowsToContents();
      ui->tvPermessi->selectRow(0);

}
Exemplo n.º 13
0
bool DatabaseManager::initDatabase() {

	SDPASSERT(Logger::instancePtr());
	Logger* log = Logger::instancePtr();

	if ( __db.isOpen() ) return false;

	QSqlQuery query1(::detectionTable);
	bool retcode = query1.exec();
	if ( retcode )
		log->addMessage(Logger::INFO, __func__, "Successfully created Detection table");
	else
		log->addMessage(Logger::CRITICAL, __func__, "Failed to create Detection table");

	QSqlQuery query2(::dispatchTable);
	retcode = query2.exec();
	if ( retcode )
		log->addMessage(Logger::INFO, __func__, "Successfully created Dispatch table");
	else
		log->addMessage(Logger::CRITICAL, __func__, "Failed to create Dispatch table");

	QSqlQuery query3(::triggerTable);
	retcode = query3.exec();
	if ( retcode )
		log->addMessage(Logger::INFO, __func__, "Successfully created Trigger table");
	else
		log->addMessage(Logger::CRITICAL, __func__, "Failed to create Trigger table");

	return retcode;
}
Exemplo n.º 14
0
void vnc::on_pushButton_clicked()
{
    Save = 1;
    if (ui->radioButton->isChecked())
        Cantidad = "0";
    else if (ui->radioButton_2->isChecked())
        Cantidad = "1";
    Cantidad1 = ui->lineEdit->text();
    Cantidad2 = ui->lineEdit_2->text();
    if (ui->checkBox->isChecked() == false)
        Cantidad3 = "0";
    else if (ui->checkBox->isChecked() == true)
        Cantidad3 = "1";
    if (ui->checkBox_2->isChecked() == false)
        Cantidad4 = "0";
    else if (ui->checkBox_2->isChecked() == true)
        Cantidad4 = "1";
    if (ui->checkBox_3->isChecked() == false)
        Cantidad5 = "0";
    else if (ui->checkBox_3->isChecked() == true)
        Cantidad5 = "1";
    if (ui->checkBox_4->isChecked() == false)
        Cantidad6 = "0";
    else if (ui->checkBox_4->isChecked() == true)
        Cantidad6 = "1";
    if (ui->checkBox_5->isChecked() == false)
        Cantidad7 = "0";
    else if (ui->checkBox_5->isChecked() == true)
        Cantidad7 = "1";
    QString cantidad;
    QSqlQuery query1(db);
    query1.exec("SELECT id FROM DatosVnc WHERE id=2");
    query1.first();
    if (query1.isValid())
        cantidad=query1.value(0).toString();
    fila=1;
    if (cantidad == "2")
    {
        QSqlRecord record= Model->record(this->fila);
        record.setValue(0,cantidad.toInt());
        record.setValue(1,Cantidad);
        record.setValue(2,Cantidad1);
        record.setValue(3,Cantidad2);
        record.setValue(4,Cantidad3);
        record.setValue(5,Cantidad4);
        record.setValue(6,Cantidad5);
        record.setValue(7,Cantidad6);
        record.setValue(8,Cantidad7);
        Model->setRecord(this->fila,record);
        Model->submitAll();
    }
    else
    {
        QMessageBox m; if (Stilo == "A") m.setStyleSheet("background-color: "+cantidad51+"; color: "+cantidad50+"; font-size: "+cantidad49+"pt; font-style: "+DatoTalla+"; font-family: "+cantidad47+"; font-weight: "+DatoNegro+"");
        m.setText(tr("No se han podido realizar los cambios. Compruebe la accesibilidad de la base de datos."));
        m.exec();
        return;
    }
}
Exemplo n.º 15
0
void CreateBooking::addStatusFields ()
{
    DbMysql* d = DbMysql::getInstance();
    QMessageBox msgBox;

    if(!d->getConnection().open())
    {
        msgBox.critical(this,"Error","Failed to connect database.1");
    }
    else
    {

        QSqlQuery query1( "select * from customer_status;" ,d->getConnection());
        if(!query1.isActive())
        {
            msgBox.critical(this,"Error","Failed to connect database.");
        }
        else
        {
            //ui->roomsList->addItem("---- Select ----",QVariant::fromValue(-1));
            while(query1.next())
            {
                ui->customer_status->addItem(query1.value(1).toString(),QVariant::fromValue(query1.value(0).toInt()));
            }

        }
        QSqlQuery query2( "select * from payment_status;" ,d->getConnection());
        if(!query2.isActive())
        {
            msgBox.critical(this,"Error","Failed to connect database.");
        }
        else
        {
            //ui->roomsList->addItem("---- Select ----",QVariant::fromValue(-1));
            while(query2.next())
            {
                ui->payment_status->addItem(query2.value(1).toString(),QVariant::fromValue(query2.value(0).toInt()));
            }

        }
        QSqlQuery query3( "select * from booking_status;" ,d->getConnection());
        if(!query3.isActive())
        {
            msgBox.critical(this,"Error","Failed to connect database.");
        }
        else
        {
            //ui->roomsList->addItem("---- Select ----",QVariant::fromValue(-1));
            while(query3.next())
            {
                ui->booking_status->addItem(query3.value(1).toString(),QVariant::fromValue(query3.value(0).toInt()));
            }

        }

    }


}
Exemplo n.º 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";
        }
Exemplo n.º 17
0
void FormGestioneFerie::on_cbCognome_currentIndexChanged(const QString &arg1)
{

    ui->cbMatricola->setCurrentIndex(ui->cbCognome->currentIndex());
    QSqlQuery query1(QString("SELECT nome FROM anagrafica where Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));
    query1.next();
    ui->lNome->setText( query1.value(0).toString() );

}
Exemplo n.º 18
0
void ordersfrm::complete()
{
	int r = QMessageBox::question(this, tr("Complete items..."),tr("Change status for completed items?"),QMessageBox::Yes, QMessageBox::No);
    if(r == QMessageBox::Yes)
    {
		int i;
		QTreeWidgetItem *item = new QTreeWidgetItem;
		for(i=0;i<treemain->topLevelItemCount();i++)
		{
				item = treemain->topLevelItem(i);
		    if(item->checkState(0))
		    {
		    	QString qstr = QString("SELECT STATUS, STOCK, DEF FROM `orders` WHERE `ID`=%1;").arg(item->text(0));
				QSqlQuery query1(qstr);
				query1.next();
		
				if(query1.value(0).toInt() < 2)
				{
				    QSqlQuery query2;
				    query2.prepare("UPDATE `orders` SET `STATUS`= :status, `DATE"+QString("%1").arg(query1.value(0).toInt()+2, 0, 10)+"`= :date WHERE `ID`=:ID LIMIT 1;");
				    query2.bindValue(":status", query1.value(0).toInt()+1);
				    query2.bindValue(":date", QDate::currentDate().toString("yyyy-MM-dd"));
				    query2.bindValue(":ID", item->text(0));
				    query2.exec();
				}
		
				if(query1.value(0).toInt() == 2)
				{
					qstr = QString("UPDATE `orders` SET `STATUS`= '%1' WHERE `ID`='%2' LIMIT 1;").arg(query1.value(0).toInt()+1).arg(item->text(0));
				    QSqlQuery query2(qstr);
		    
		    		qstr = QString("SELECT NAME, USERS FROM datatables WHERE `DESCRIPTION`='%1';").arg(query1.value(1).toString());
				    QSqlQuery query3(qstr);
				    query3.next();
				    QString stock = query3.value(0).toString();
		    
		    		qstr = QString("SELECT ID, col3 FROM %1 WHERE `col1`= '%2';").arg(stock).arg(item->text(2));
		    		QSqlQuery query4(qstr);
				    query4.next();
				    QString id = query4.value(0).toString();
				    QString old_q = query4.value(1).toString();
		    	    
		    	    qstr = QString("UPDATE `%1` SET `col3`= '%2' WHERE `ID`= '%3' LIMIT 1;").arg(stock).arg(old_q.toInt() + item->text(4).toInt()).arg(id);
				    QSqlQuery query5(qstr);
				    QMessageBox::question(this, tr("Complete items..."), query5.executedQuery());
				}
		    }
		}
		loadentries();
		countentries();
    }
}
Response::ResponseCode ServerSocketInterface::cmdReplayList(const Command_ReplayList & /*cmd*/, ResponseContainer &rc)
{
    if (authState != PasswordRight)
        return Response::RespFunctionNotAllowed;

    Response_ReplayList *re = new Response_ReplayList;

    QSqlQuery query1(sqlInterface->getDatabase());
    query1.prepare("select a.id_game, a.replay_name, b.room_name, b.time_started, b.time_finished, b.descr, a.do_not_hide from cockatrice_replays_access a left join cockatrice_games b on b.id = a.id_game where a.id_player = :id_player and (a.do_not_hide = 1 or date_add(b.time_started, interval 7 day) > now())");
    query1.bindValue(":id_player", userInfo->id());
    sqlInterface->execSqlQuery(query1);
    while (query1.next()) {
        ServerInfo_ReplayMatch *matchInfo = re->add_match_list();

        const int gameId = query1.value(0).toInt();
        matchInfo->set_game_id(gameId);
        matchInfo->set_room_name(query1.value(2).toString().toStdString());
        const int timeStarted = query1.value(3).toDateTime().toTime_t();
        const int timeFinished = query1.value(4).toDateTime().toTime_t();
        matchInfo->set_time_started(timeStarted);
        matchInfo->set_length(timeFinished - timeStarted);
        matchInfo->set_game_name(query1.value(5).toString().toStdString());
        const QString replayName = query1.value(1).toString();
        matchInfo->set_do_not_hide(query1.value(6).toBool());

        {
            QSqlQuery query2(sqlInterface->getDatabase());
            query2.prepare("select player_name from cockatrice_games_players where id_game = :id_game");
            query2.bindValue(":id_game", gameId);
            sqlInterface->execSqlQuery(query2);
            while (query2.next())
                matchInfo->add_player_names(query2.value(0).toString().toStdString());
        }
        {
            QSqlQuery query3(sqlInterface->getDatabase());
            query3.prepare("select id, duration from " + servatrice->getDbPrefix() + "_replays where id_game = :id_game");
            query3.bindValue(":id_game", gameId);
            sqlInterface->execSqlQuery(query3);
            while (query3.next()) {
                ServerInfo_Replay *replayInfo = matchInfo->add_replay_list();
                replayInfo->set_replay_id(query3.value(0).toInt());
                replayInfo->set_replay_name(replayName.toStdString());
                replayInfo->set_duration(query3.value(1).toInt());
            }
        }
    }

    rc.setResponseExtension(re);
    return Response::RespOk;
}
Exemplo n.º 20
0
void ZhscWidget::bookmark()
{
  QString tmp;
  Bookmark bm;
  QString dynasty, poet, poem;

  bml.clear();

  QString sq2 = "select * from tsc";
  QSqlQuery query2( sq2 );

  if ( bConStatus )
  {
    QString sq1 = "select dynastyno, poetno, poemno from bookmark order by id";
    QSqlQuery query1( sq1 );

    if ( query1.size() > 0 )
    {
      while ( query1.next() )
      {
        dynasty = query1.value(0).toString();
        poet = query1.value(1).toString();
        poem = query1.value(2).toString();

        bm.dynastyno = dynasty;
        bm.poetno = poet;
        bm.poemno = poem;

        sq2 = "select dynasty, poet, caption from tsc where dynastyno = '" + dynasty + "' and poetno = '" + poet + "' and poemno = '" + poem + "'";
        query2.exec( sq2 );

        if ( query2.size() > 0 )
        {
          if ( query2.next() )
          {
            tmp = trUtf8( query2.value(0).toByteArray() ) + "-" 
              + trUtf8( query2.value(1).toByteArray() ) + "-"
              + trUtf8( query2.value(2).toByteArray() );

            bm.content = tmp;

            bml.append( bm ); 
          }
        }
      }
    }

    emit bookmarkChanged( bml );
  }
}
Exemplo n.º 21
0
//存入数据库
void Add_user_data::add_thedata_todata()
{
    userdataname = "User_Data_";
    userdata = dbopen.initDatabase("User_recode.db");
    QSqlQuery query(userdata);
    query.exec("select * from User_recode");
    while (query.last())
    {
        userdataname += query.value(1).toString();
        userdataname +=".db";
        dbopen.closedb();
        break;
    }
    QString usertip;
    if(tag1)
    {
        usertip = "存入";
    }
    else if(!tag1)
    {
        usertip = "支出";
    }
    userdata = dbopen.initDatabase(userdataname);
    QSqlQuery query1(userdata);
    user_add_number = ui->text_number->text();
    user_add_time = ui->time->text();
    user_add_money = ui->Add_money->text();
    user_add_remark = ui->Add_backup->toPlainText();
    QString querysql = "insert into UserData values('";
    querysql += user_add_number;
    querysql += "','";
    querysql += user_add_time;
    querysql += "','";
    querysql += usertip;
    querysql += "','";
    querysql += user_add_what;
    querysql += "','";
    querysql += user_add_money;
    querysql += "','";
    querysql += user_add_tip;
    querysql += "','";
    querysql += user_add_remark;
    querysql += "')";
    query1.exec(querysql);
    dbopen.closedb();
    accept();
}
Exemplo n.º 22
0
/*!
 * \brief DBthread::newDB
 * \param query
 * \param DBname
 *
 *  Slot for creating a new db and all the tables needed inside it.
 */
void DBthread::newDB(QString query, QString DBname){
    QSqlQuery query1(query);
    if(query1.isActive())
        qDebug()<<"Base de Datos Creada";
    else{
        if(result){
            result = false;
            emit querResult(result,query1.lastError().text());
            qDebug()<<"Base de Datos no Creada";
        }
    }
    QSqlQuery query2("use " + DBname);
    if(query2.isActive())
        qDebug()<<"Colocado en la base de datos " << DBname;
    else{
        if(result){
            result = false;
            emit querResult(result,query2.lastError().text());
            qDebug() << query2.lastError();
        }
    }
    QSqlQuery PlayTab("create table if not exists players(id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, player_label VARCHAR(10) NOT NULL, PRIMARY KEY(id))");
    if(PlayTab.isActive())
        qDebug()<<"Tabla de jugadores creada";
    else{
        if(result){
            result = false;
            emit querResult(result,PlayTab.lastError().text());
        qDebug()<<"Tabla de jugadores no creada";
        }
    }
    QSqlQuery FrameTab("create table if not exists data(id INT UNSIGNED NOT NULL AUTO_INCREMENT,frame BIGINT UNSIGNED NOT NULL, player_id TINYINT UNSIGNED NOT NULL, xpos DOUBLE PRECISION UNSIGNED NOT NULL, ypos DOUBLE PRECISION UNSIGNED NOT NULL, FOREIGN KEY (player_id) REFERENCES players(id) ON DELETE CASCADE, PRIMARY KEY (id))");
    if(FrameTab.isActive())
        qDebug()<<"Tabla de datos creada";
    else{
        if(result){
            result = false;
            emit querResult(result,FrameTab.lastError().text());
            qDebug()<<"Tabla de datos no creada";
        }
    }
    if(result){
        qDebug() << result;
        emit querResult(result,QString());
    }
}
Exemplo n.º 23
0
bool Reservation::CheckAvailability(){
    DatabaseManager *dbm = DatabaseManager::Instance();
    // try to open database

    if(!dbm->db.open()){
        QMessageBox::critical(0, QObject::tr("Database Error"),dbm->db.lastError().text());
    }

    // if opened
    else{               // selecting only those rooms which are not available during this time
        QSqlQuery query("SELECT Rooms FROM `Residing_Customer` WHERE ( CheckIn_Date <= '"+QString::fromStdString(CheckInDate)+"' AND CheckOut_Date >= '"+QString::fromStdString(CheckInDate)+"') OR ( CheckIn_Date <= '"+QString::fromStdString(CheckOutDate)+"' AND CheckOut_Date >= '"+QString::fromStdString(CheckOutDate)+"')",dbm->db);
        if(!query.isActive()){
            QMessageBox::critical(0, QObject::tr("Query check Error"),query.lastError().text());
        }

        QList<int> unavailableRooms;
        while(query.next()){
            QStringList list = query.value(query.record().indexOf("Rooms")).toString().split(";");
             while(!list.isEmpty()){
                 unavailableRooms.push_back(list.front().toInt());   //putting those room in vector of unavailable rooms
                 list.pop_front();
             }
        }
        for(int i=0;i<NumberOfRooms;i++){       // iterating through list of rooms where room are type of required room
            QSqlQuery query1("SELECT room_no FROM Rooms WHERE room_no LIKE '"+QString::number(RequiredRooms[i].RoomType)+"%'",dbm->db);
            if(!query1.isActive()){
                QMessageBox::critical(0, QObject::tr("Query room allot Error"),query1.lastError().text());
            }

            while(query1.next()){
                int roomno = query1.value(0).toInt();
                if(!unavailableRooms.contains(roomno)){
                    RequiredRooms[i].RoomNumber = roomno;               //if current room is not in unavailable list
                    RequiredRooms[i].Status = "Available";              //then allocate room no to required rooms
                    unavailableRooms.push_back(roomno);                // and add it to unavailable list
                    break;
                }
            }
            if(RequiredRooms[i].Status.compare("Available")){    //if room is not available return false
                return false;
            }
        }
    }
    return true;
}
Exemplo n.º 24
0
void CreateBooking::addCustomersInForm()
{

    DbMysql* d = DbMysql::getInstance();
    QMessageBox msgBox;

    QCompleter* cl = new QCompleter(this);
    QStandardItemModel *model = new QStandardItemModel(cl);


    //ui->roomsList->setCurrentText("-----Select-----");
    if(!d->getConnection().open())
    {
        msgBox.critical(this,"Error","Failed to connect database.1");
    }
    else
    {

        QSqlQuery query1( "select customer_id,customer_name from customers order by customer_id desc;" ,d->getConnection());
        if(!query1.isActive())
        {
            msgBox.critical(this,"Error","Failed to connect database.");
        }
        else
        {
            //ui->roomsList->addItem("---- Select ----",QVariant::fromValue(-1));
            while(query1.next())
            {
                QStandardItem *item = new QStandardItem;
                item->setText(query1.value(1).toString());
                item->setData(query1.value(0).toInt(), Qt::UserRole);
                model->appendRow(item);

            }

        }

    }
    cl->setCaseSensitivity(Qt::CaseInsensitive);
    cl->setModel(model);
    ui->c_customer_name->setCompleter(cl);

    //ui->c_customer_name
    connect(cl, SIGNAL(activated(QModelIndex)),this, SLOT(onItemActivated(QModelIndex)));
}
Exemplo n.º 25
0
FormGestioneFerie::FormGestioneFerie(QSqlDatabase db, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormGestioneFerie)
{
    ui->setupUi(this);

    QDate oggi;
    ui->dePermessiDal->setDate(oggi.currentDate());
    ui->dePermessiAl->setDate(oggi.currentDate());

    this->db= db;



    QSqlQuery query(QString("SELECT Matricola,cognome FROM anagrafica"));
    while (query.next())
    {
     ui->cbMatricola->addItem(  query.value(0).toString() );
     ui->cbCognome->addItem(  query.value(1).toString() );
     ui->lNome->setText( query.value(2).toString() );
    }
    QSqlQuery query1(QString("SELECT nome FROM anagrafica where Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));
    query1.next();
    ui->lNome->setText( query1.value(0).toString() );



    QSqlTableModel *model = new QSqlTableModel(this, this->db);
    model->setTable("assenze");
    model->setEditStrategy(QSqlTableModel::OnFieldChange);
    model->select();
    model->setFilter(QString("Matricola=\"%1\"").arg(ui->cbMatricola->currentText()));
    model->sort(2,Qt::AscendingOrder);
    model->setHeaderData(1, Qt::Horizontal, tr("MATRICOLA"));
    model->setHeaderData(2, Qt::Horizontal, tr("DATA"));
    model->setHeaderData(3, Qt::Horizontal, tr("CAUSA"));
    ui->tvPermessi->setModel(model);
    ui->tvPermessi->hideColumn(0);
    ui->tvPermessi->resizeColumnsToContents();
    ui->tvPermessi->resizeRowsToContents();
    ui->tvPermessi->selectRow(0);


}
Exemplo n.º 26
0
void Database::NewDatabase(const std::string& filename)
{
    m_db.setDatabaseName(filename.c_str());
    if(!m_db.open())
    {
        std::cerr << "error: Unknown error" << std::endl;
        QMessageBox::information(0,"Ok","Unknown error");
    }
    QSqlQuery query1("CREATE TABLE FileInfo ( id int )");
    QSqlQuery query2("insert into FileInfo (id) values (1)");
    QSqlQuery query3("CREATE TABLE Log(ID INT PRIMARY KEY NOT NULL, \
                                       Log TEXT, \
                                       Date DATE, \
                                       PersonID INT, Title TEXT);");
    QSqlQuery query4("CREATE TABLE Person( \
                                     ID INT PRIMARY KEY NOT NULL, \
                                     Name   TEXT \
                                     );");
}
Exemplo n.º 27
0
void ZhscWidget::historyNext()
{
  bool ok = FALSE;

  if ( bConStatus )
  {
    if ( ( nHistoryIndex != -1 ) && ( nHistoryMax != -1 ) && ( nHistoryIndex < nHistoryMax ) )
    {
      QString sid1;
      sid1.setNum( nHistoryIndex );

      QString sq1 = "select min(id - " + sid1 + ") from history where id - " + sid1 + " > 0";
      QSqlQuery query1( sq1 );

      if ( query1.size() > 0 )
      {
        if ( query1.next() )
        {
          QString min;
          min.setNum( query1.value(0).toInt( &ok ) );

          QString sq2 = "select id, dynastyno, poetno, poemno, history from history where id - " + sid1 + " = " + min;
          QSqlQuery query2( sq2 );

          if ( query2.size() > 0 )
          {
            if ( query2.next() )
            {
              nHistoryIndex = query2.value(0).toInt( &ok );
              sDynastyNo = query2.value(1).toString();
              sPoetNo = query2.value(2).toString();
              sPoemNo = query2.value(3).toString();
              dtHistoryDT = query2.value(4).toDateTime();

              setPoem();
              history();
            }
          }
        }
      }
    }
  }
}
Exemplo n.º 28
0
void ZhscWidget::recordNext()
{
  bool ok = FALSE;

  if ( bConStatus )
  {
    if ( ( nPoemIndex != 0 ) && ( nPoemMax != 0 ) && ( nPoemIndex < nPoemMax ) )
    {
      QString sid1;
      sid1.setNum( nPoemIndex );

      QString sq1 = "select min(id - " + sid1 + ") from tsc where id - " + sid1 + " > 0";
      QSqlQuery query1( sq1 );

      if ( query1.size() > 0 )
      {
        if ( query1.next() )
        {
          QString min;
          min.setNum( query1.value(0).toInt( &ok ) );

          QString sq2 = "select id, dynastyno, poetno, poemno from tsc where id - " + sid1 + " = " + min;
          QSqlQuery query2( sq2 );

          if ( query2.size() > 0 )
          {
            if ( query2.next() )
            {
              nPoemIndex = query2.value(0).toInt( &ok );
              sDynastyNo = query2.value(1).toString();
              sPoetNo = query2.value(2).toString();
              sPoemNo = query2.value(3).toString();

              setPoem();
              record();
            }
          }
        }
      }
    }
  }
}
Exemplo n.º 29
0
int CreateBooking::genBookingId()
{
    DbMysql* d = DbMysql::getInstance();

    if(!d->getConnection().open())
    {
        //msgBox.critical(this,"Error","Failed to connect database.1");
        return 0;
    }
    else
    {
        QSqlQuery query1("select max(booking_id) from booking;",d->getConnection());

        if(query1.isActive())
        {
            query1.next();
            return query1.value(0).toInt()+1;
        }
        else return 0;
    }
}
Exemplo n.º 30
0
void HotelInfo::addHotelInfoInForm()
{
    DbMysql* d = DbMysql::getInstance();
    QMessageBox msgBox;

    if(!d->getConnection().open())
    {
        msgBox.critical(this,"Error","Failed to connect database.1");
    }
    else
    {
        QString sql = "select * from hotel_info where hotel_info_id=1;";

        QSqlQuery query1(sql,d->getConnection());
        qDebug()<<query1.lastQuery();
        if(!query1.isActive())
        {
            msgBox.critical(this,"Error","Failed to connect database.");
        }
        else
        {
            query1.next();
            ui->hotelName->setText(query1.value(1).toString());
            ui->address->setPlainText(query1.value(2).toString());
            ui->city->setText(query1.value(3).toString());
            ui->dist->setText(query1.value(4).toString());
            ui->state->setText(query1.value(5).toString());
            ui->pin->setText(query1.value(6).toString());
            ui->phone1->setText(query1.value(7).toString());
            ui->phone2->setText(query1.value(8).toString());
            ui->email->setText(query1.value(9).toString());
            ui->website->setText(query1.value(10).toString());
            ui->cperson->setText(query1.value(11).toString());
            ui->taxId->setText(query1.value(12).toString());

        }
    }
}