void Hospital2ruralcooperative::writeindb(QString strNo)
{
	sql.connect2();
	QSqlQuery query(*sql.db);	
	QSqlQuery query2(sql.db2);	
	query2.exec("select * from HIS.t_con1");
	int icount=0;
	while(query2.next())
	{
		icount++;
	}
	int itotalcount=icount+1;
	query2.prepare("delete from HIS.t_con1 where Zyh1 = '"+strNo+"'");
	query2.exec();
	query2.prepare("delete from HIS.t_con2 where Zyh = '"+strNo+"'");
	query2.exec();
	query.exec("select * from zy_patientinfo where hospitalisationno= '"+strNo+"'");
	while(query.next())
	{
		//QSqlQuery query2(*sql.db);
		query2.prepare("insert into HIS.t_con1 values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
		//QString strsign = query.value(0).toString();
		//if (strsign.length()==1)
		//{
		//	strsign = "00000"+strsign;
		//}
		//if (strsign.length()==2)
		//{
		//	strsign = "0000"+strsign;
		//}
		//if (strsign.length()==3)
		//{
		//	strsign = "000"+strsign;
		//}
		//if (strsign.length()==4)
		//{
		//	strsign = "00"+strsign;
		//}
		//if (strsign.length()==5)
		//{
		//	strsign = "0"+strsign;
		//}
		query2.bindValue(0, query.value(27).toString());//标识住院号
		query2.bindValue(1, query.value(1).toString());
		query2.bindValue(2, query.value(25).toString());
		query2.bindValue(3, query.value(26).toDateTime());
		query2.bindValue(4, 5);
		query2.bindValue(5, query.value(4).toString());
		QString strgender = query.value(5).toString();
		if (strgender==QString::fromLocal8Bit("男"))
		{
			query2.bindValue(6, 1);
		}
		if (strgender==QString::fromLocal8Bit("女"))
		{
			query2.bindValue(6, 2);
		}

		query2.bindValue(7,  query.value(7).toString());

		query2.bindValue(8, NULL);//出生日期
		query2.bindValue(9,  query.value(2).toDateTime());

		QSqlQuery query3(*sql.db);
		query3.exec("select * from zy_pay where hospitalisationno= '"+strNo+"'");
		double totalpay=0;
		while(query3.next())
		{
			totalpay +=query3.value(8).toDouble();
		}
		query2.bindValue(10, totalpay);


		query2.bindValue(11, query.value(2).toDateTime());
		query2.bindValue(12, query.value(23).toDateTime());
		query2.bindValue(13, query.value(20).toString());

		query2.bindValue(14, 0);
		query2.bindValue(15, NULL);

		query2.bindValue(16, NULL);
		query2.bindValue(17, NULL);
		query2.bindValue(18, NULL);
		query2.bindValue(19, NULL);
		query2.bindValue(20, NULL);
		query2.bindValue(21, NULL);
		query2.bindValue(22, NULL);


		query2.bindValue(23, NULL);
		query2.bindValue(24, NULL);

		query2.bindValue(25, NULL);
		query2.bindValue(26, NULL);

		query2.bindValue(27, NULL);
		query2.bindValue(28, NULL);

		query2.bindValue(29, NULL);
		query2.bindValue(30, NULL);


		query2.bindValue(31, NULL);
		query2.bindValue(32,query.value(18).toString());

		query2.bindValue(33, NULL);

		query2.bindValue(34, query.value(17).toString());
		query2.bindValue(35, query.value(14).toString());
		query2.bindValue(36, query.value(13).toString());
		query2.bindValue(37, query.value(10).toString());

		if(query2.exec())
		{
			//QMessageBox::information(this,QString ::fromLocal8Bit("提示"),QString::fromLocal8Bit("保存成功!"));
		}
	}
	int count=0;
	query2.exec("select * from HIS.t_con2");
	while(query2.next())
	{
		count++;
	}
	query.exec("select * from zy_chargedetail where hospitalisationno= '"+strNo+"'");
	while(query.next())
	{
		/*QSqlQuery query2(*sql.db);*/
		count++;
		query2.prepare("insert into HIS.t_con2 values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
		query2.bindValue(0, count);
		query2.bindValue(1, NULL);
		query2.bindValue(2, query.value(10).toString());
		query2.bindValue(3,query.value(9).toDateTime());
		query2.bindValue(4, "");

		int drugflag = query.value(11).toInt();
		query2.bindValue(5,drugflag);//医药分类
		query2.bindValue(6,NULL);
		query2.bindValue(8,NULL);
		QString strdrug =query.value(4).toString();
		if (drugflag==1)
		{
			QSqlQuery query3(*sql.db);	
			
			query3.exec("select * from sys_drugcorrespondence where yymc= '"+strdrug+"'");
			while (query3.next())
			{
				query2.bindValue(6, query3.value(1).toString());
				query2.bindValue(7, query3.value(3).toString());
				query2.bindValue(8, query3.value(2).toString());
				query2.bindValue(9, query3.value(4).toString());

				query2.bindValue(20, NULL);//医疗项目分类
			}
		}
		if (drugflag==2)
		{
			QSqlQuery query3(*sql.db);	
			QString strdrugtype,nhcode,nhname,hiscode,hisname;
			query3.exec("select * from sys_projectcorrespondence where yymc= '"+strdrug+"'");
			while (query3.next())
			{
				query2.bindValue(6, query3.value(1).toString());
				query2.bindValue(7, query3.value(3).toString());
				query2.bindValue(8, query3.value(2).toString());
				query2.bindValue(9, query3.value(4).toString());
				query2.bindValue(20, query3.value(7).toString());//医疗项目分类
			}
		}
		if (drugflag==3)
		{
			QSqlQuery query3(*sql.db);		
			QString strdrugtype,nhcode,nhname,hiscode,hisname;
			query3.exec("select * from sys_materialcorrespondence where yymc= '"+strdrug+"'");
			while (query3.next())
			{
				query2.bindValue(6, query3.value(1).toString());
				query2.bindValue(7, query3.value(3).toString());
				query2.bindValue(8, query3.value(2).toString());
				query2.bindValue(9, query3.value(4).toString());
				query2.bindValue(20, NULL);//医疗项目分类
			}
		}
		//
		//query2.bindValue(6, 6);
		//query2.bindValue(7, 7);
		//query2.bindValue(8, "");
		//query2.bindValue(9, query.value(4).toString());

		query2.bindValue(10, query.value(7).toDouble());
		query2.bindValue(11, query.value(6).toDouble());
		query2.bindValue(12, query.value(8).toDouble());//金额
		QSqlQuery query3(*sql.db);	
		query3.exec("select * from sys_drugdictionary where name= '"+query.value(4).toString()+"'");
		while (query3.next())
		{
			QString strdrugtype = query3.value(14).toString();
			if (strdrugtype==QString::fromLocal8Bit("西药"))
			{
				query2.bindValue(13, 1);
			}
			else if (strdrugtype==QString::fromLocal8Bit("中成药"))
			{
				query2.bindValue(13, 2);
			}
			else if (strdrugtype==QString::fromLocal8Bit("中草药"))
			{
				query2.bindValue(13, 3);
			}
		}
		query2.bindValue(14, 1);//药品属性
		query2.bindValue(15, NULL);
		query2.bindValue(16, NULL);
		query2.bindValue(18, NULL);

		query2.bindValue(19, NULL);
		////医疗项目分类
		query2.bindValue(21, NULL);
		query2.bindValue(22, NULL);
		query2.bindValue(23, NULL);
		query2.bindValue(24, NULL);
		query2.bindValue(25, NULL);
		query2.bindValue(26, NULL);
		query2.bindValue(27, NULL);
		query2.bindValue(28, NULL);
		query2.bindValue(29, NULL);
		query2.bindValue(30, NULL);
		query2.bindValue(31, NULL);
		query2.bindValue(32, NULL);
		if(query2.exec())
		{
			//QMessageBox::information(this,QString ::fromLocal8Bit("提示"),QString::fromLocal8Bit("保存成功!"));
		}
	}


	query.prepare("UPDATE zy_patientinfo SET out2cooperativeflag= ? WHERE hospitalisationno = '"+strNo+"'");
	query.bindValue(0,1);
	query.exec();
	sql.disconnect2();
}
int main()
{
	int i;
	FILE *fin  = fopen ("packrec.in", "r");
    FILE *fout = fopen ("packrec.out", "w");
	for(i=1;i<=4;i++)
	{
		fscanf(fin,"%d %d",a+i,b+i);
	}
	query1(1,0,0);
	query2(1,0,0);
	swap(1,4);
	query2(1,0,0);
	swap(1,4);
	swap(2,4);
	query2(1,0,0);
	swap(2,4);
	swap(3,4);
	query2(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	swap(1,3);
	query3(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	swap(1,3);
	swap(2,3);
	query3(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	swap(2,3);
	swap(1,4);
	query3(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	swap(1,4);
	swap(2,4);
	query3(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	swap(2,4);
	swap(1,3);
	swap(2,4);
	query3(1,0,0);
	swap(3,4);
	query3(1,0,0);
	swap(3,4);
	swap(2,4);
	swap(1,3);
	query4(1,0,0);
	swap(1,3);
	query4(1,0,0);
	swap(1,3);
	swap(1,4);
	query4(1,0,0);
	swap(1,4);
	swap(2,3);
	query4(1,0,0);
	swap(2,3);
	swap(2,4);
	query4(1,0,0);
	swap(2,4);
	swap(1,3);
	swap(2,4);
	query4(1,0,0);
	swap(2,4);
	swap(1,3);
	query5(1,0,0,0,0);
	swap(1,3);
	query5(1,0,0,0,0);
	swap(1,3);
	swap(1,4);
	query5(1,0,0,0,0);
	swap(1,4);
	swap(2,3);
	query5(1,0,0,0,0);
	swap(2,3);
	swap(2,4);
	query5(1,0,0,0,0);
	swap(1,3);	swap(1,3);
	swap(2,4);
	query5(1,0,0,0,0);
	swap(2,4);
	swap(1,3);
	quick_sort(0,cur-1);
	flag=p[0];
	wa=0;
	fprintf(fout,"%d\n%d %d\n",max,p[0],max/p[0]);
	while(wa<cur)
	{
		if(p[wa]==flag)
		{
			wa++;
			continue;
		}
		else
		{
			if(p[wa]>max/p[wa])
				break;
			fprintf(fout,"%d %d\n",p[wa],max/p[wa]);
			flag=p[wa];
		}
	}
	return 0;
}
Exemple #3
0
//! ---------------- addToDatabase ---------------------------------------------
void HistoManager::addToDatabase()
{
    m_timer->stop();

    if(Engine::instance()->state() != ENGINE::PLAYING) {
       m_timer->stop();
       return;
    }

    MEDIA::TrackPtr media   =  m_player->playingTrack();
    int       now_date      =  QDateTime::currentDateTime().toTime_t();

    QString   engine_url    =  media->url;
    if(engine_url.isEmpty())
      return;

    QString   media_name;
    if(media->type() == TYPE_TRACK)
      media_name = media->artist + " - " + media->album + " - " + media->title;
    else
      media_name = media->name;

    Database db;
    if (!db.connect()) return;

    QSqlQuery("BEGIN TRANSACTION;",*db.sqlDb());

    //---------------------------------------
    //    add or update entry in history
    //---------------------------------------
    QSqlQuery q("", *db.sqlDb());
    q.prepare("SELECT `id`,`url` FROM `histo` WHERE `url`=:val;");
    q.bindValue(":val", engine_url );
    q.exec();

    if ( !q.next() ) {
      Debug::debug() << "[Histo] add a new entry" << engine_url;

      q.prepare("INSERT INTO `histo`(`url`,`name`,`date`) VALUES (:u,:n,:d);");
      q.bindValue(":u", engine_url);
      q.bindValue(":n", media_name);
      q.bindValue(":d", now_date);
      q.exec();

      if(q.numRowsAffected() < 1)
        Debug::warning() << "[Histo] error adding entry !! ";

      QSqlQuery query("DELETE FROM `histo` WHERE `id` <= (SELECT MAX(`id`) FROM `histo`) - 2000;", *db.sqlDb());
    }
    else
    {
      Debug::debug() << "[Histo] update an existing entry" << engine_url;
      int histo_id = q.value(0).toString().toInt();

      q.prepare("UPDATE `histo` SET `date`=:d WHERE `id`=:id;");
      q.bindValue(":d", now_date);
      q.bindValue(":id", histo_id);
      q.exec();
    }

    //---------------------------------------
    //    update playcount
    //---------------------------------------
    q.prepare("SELECT `id`,`artist_id`,`album_id` FROM `view_tracks` WHERE `filename`=:val LIMIT 1;");
    q.bindValue(":val", engine_url );
    q.exec();

    if (q.next())
    {
      //Debug::debug() << "update playcount!";

      const int trackId  = q.value(0).toInt();
      const int artistId = q.value(1).toInt();
      const int albumId  = q.value(2).toInt();

      QSqlQuery query1("UPDATE `tracks` " \
                       "SET `playcount`=`playcount`+1 " \
                       "WHERE `id`="+QString::number(trackId)+";", *db.sqlDb());

      QSqlQuery query2("UPDATE `albums` " \
                       "SET `playcount`=`playcount`+1 " \
                       "WHERE `id`="+QString::number(albumId)+";", *db.sqlDb());

      QSqlQuery query3("UPDATE `artists` " \
                       "SET `playcount`=`playcount`+1 " \
                       "WHERE `id`="+QString::number(artistId)+";", *db.sqlDb());

      /* update collection model item */
      MEDIA::TrackPtr track = MEDIA::TrackPtr(
               LocalTrackModel::instance()->trackItemHash.value(trackId)
               );

      if(!track.isNull()) {
        track->playcount++;
        track->lastPlayed = now_date;

        MEDIA::AlbumPtr album = MEDIA::AlbumPtr::staticCast(track->parent());
        album->playcount++;

        MEDIA::ArtistPtr artist = MEDIA::ArtistPtr::staticCast(album->parent());
        artist->playcount++;
      }
    }


    QSqlQuery("COMMIT TRANSACTION;",*db.sqlDb());
}
Exemple #4
0
int Bench(int argc,char **argv)
{
	REF(Module)  moduleH;
	REF(any) r;
	char moduleName[40];
	// ProcessStats    totalTime;
	// ServerStats     totalSrvTime;
	//char*	purgeVar;
	char  resultText[200];  // buffer to hold result of operation for
                                // printing outside of timing region.
	char *configfile;
	int opIndex = 2;
	int repeatCount = 1;
	BenchmarkOp whichOp = Trav1;
	bool manyXACTS = 0;

	w_rc_t rc;

#ifdef PARSETS

	LOID objtype;

	int NumNodes;

	//reinitialize some globals.
	nextAtomicId=0; 
	nextCompositeId=0;
	nextComplexAssemblyId=0;
	nextBaseAssemblyId=0;
	nextModuleId = TotalModules;
	initParSets(argc, argv);

	if (argc < 6){
	    fprintf(stderr, "Usage: %s %s\n", argv[0], usage1);
	    fprintf(stderr, "%s\n", usage3);
	    fprintf(stderr, "%s\n", usage4);

	    exit(1);
	}

	sscanf(argv[5], "%d", &NumNodes);
	printf("NUMNODES = %d\n", NumNodes);

	for (int j=0; j< NumNodes; j++)
	  CompNodes.Add(j+1);

#endif

	rc = initialize(argc, argv, usage1);
	if(rc) {
	    return 1;
	}

	rc = Shore::begin_transaction(3);
	if(rc){
	    cerr << "can't begin transaction: " << rc << endl;
	    return 1;
	}

	// initialize parameters for benchmark.
	ParseCommandLine(argc, argv, opIndex, repeatCount, whichOp, manyXACTS,
		&configfile);

#ifdef PARSETS
	SetParams(argv[1], slArgs);
#else
	SetParams(configfile);
#endif
	rc = InitGlobals();
	if(rc){
	    cerr << "Error in InitGlobals: " << rc << endl;
	    exit(1);
	}

	nextAtomicId  = TotalAtomicParts + 1;
	nextCompositeId = TotalCompParts + 1;

	rc = Shore::commit_transaction();
	if(rc){
	    cerr << "can't commit transaction: " << rc << endl;
	    return 1;
	}

#ifdef PARSETS


	SlaveRPC(CompNodes, (char *) slaveGenInit, (char *)&slArgs, sizeof(SlaveArgs));	
	SlaveRPC(CompNodes, (char *)slaveOpenPools, NULL, -1);	

#ifdef NEWCOMMUNICATION
	myParSetServer->CreateParSet("oo7db", "CompositePart", ParSet::kPrimary, objtype,(char *)createCompositePart, 4, CompNodes, ParSet::kUserDef, 
		     (char *)declusterCompositeParts);
#else
	CreateParSet("oo7db", "CompositePart", ParSet::kPrimary, objtype,
		     4, (char *)createCompositePart, CompNodes, 
		     ParSet::kUserDef, (char *)declusterCompositeParts);

#endif

	compositeParSet = new PrimaryParSet <REF(CompositePart)>("oo7db", "CompositePart");
#endif

	// Compute structural info needed by the update operations,
        // since these operations need to know which id's should
        // be used next.

	int baseCnt = NumAssmPerAssm;
	int complexCnt = 1;	for (int i = 1; i < NumAssmLevels-1; i++) {
            baseCnt = baseCnt * NumAssmPerAssm;
            complexCnt += complexCnt * NumAssmPerAssm;
	}
	nextBaseAssemblyId = TotalModules*baseCnt + 1;
	nextComplexAssemblyId = TotalModules*complexCnt + 1;
	nextAtomicId = TotalAtomicParts + 1;
	nextCompositeId = TotalCompParts + 1;


	// needed for insert and delete tests
	shared_cp = new BAIdList[TotalCompParts+NumNewCompParts+1];
	private_cp = new BAIdList[TotalCompParts+NumNewCompParts+1];


	// See if debug mode is desired, see which operation to run,
	// and how many times to run it.



	// totalTime.Start();
	// totalSrvTime.Start();

	enum {do_commit, do_chain, do_nothing, do_begin } choice=do_begin;

        // Actually run the darn thing.
	for (int iter = 0; iter < repeatCount; iter++) 
	{
	    //////////////////////////////////////////////////////////////////
	    // Run an OO7 Benchmark Operation
	    //
	    //////////////////////////////////////////////////////////////////

	    printf("RUNNING OO7 BENCHMARK OPERATION %s, iteration = %d.\n", 
	           argv[opIndex], iter);

  	    // get wall clock time
            gettimeofday(&startWallTime, IGNOREZONE &ignoreTimeZone);

	    // get starting usage values.
	    getrusage(RUSAGE_SELF, &startUsage);

	    // Start a new transaction if either this is the first iteration
	    // of a multioperation transaction or we we are running each
	    // operate as a separate transaction

#ifdef PARSETS
	    if(choice == do_begin) {
		W_COERCE(Shore::begin_transaction(3));
		SlaveRPC(CompNodes, (char *)slaveBeginTransaction, NULL, -1);
	    }

#else
	    if(choice == do_begin) {
		// E_BeginTransaction();
		W_COERCE(Shore::begin_transaction(3));
	    }
#endif

            // set random seed so "hot" runs are truly hot
            srandom(1);

	    // Use random module for the operation
//            int moduleId = (int) (random() % TotalModules) + 1;
	for (int moduleId = 1 ; moduleId <= TotalModules; moduleId++){
			
#ifdef USE_MODULE_INDEX
            sprintf(moduleName, "Module %08d", moduleId);
//	    printf("moduleName=%s\n",moduleName);
	    moduleH =  tbl->ModuleIdx.find(moduleName);
#else
	    sprintf(moduleName,"Module%d", moduleId);
	    rc = REF(Module)::lookup(moduleName, moduleH);
	    if(rc){
		cerr << "Can't find module " << moduleName << ": "
		     << rc << endl;
		return 1;
	    }
#endif
	    printf("Traversing Module= %s\n", moduleName);
	    if (moduleH == NULL)
	    {
	        fprintf(stderr, "ERROR: Unable to access %s.\n", moduleName);
		// E_AbortTransaction();
		W_COERCE(Shore::abort_transaction());
	        exit(1);
	    }

	    // Perform the requested operation on the chosen module
	    long count = 0;
	    int docCount = 0;
	    int charCount = 0;
	    int replaceCount = 0;

	    switch (whichOp) {
	        case Trav1:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 1 DFS visited %d atomic parts.\n",
			             count);
  		    break;
		 case Trav1WW:
                    RealWork = 1;
                    whichOp = Trav1;  // so traverse methods don't complain
                    count = moduleH->traverse(whichOp);
                    whichOp = Trav1WW;  // for next (hot) traversal
                    sprintf(resultText, "Traversal 1WW DFS visited %d atomic parts.\n",
                                     count);
                    break;
	        case Trav2a:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 2A swapped %d pairs of (X,Y) coordinates.\n",
 			         count);
		    break;
	        case Trav2b:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 2B swapped %d pairs of (X,Y) coordinates.\n",
			             count);
		    break;
	        case Trav2c:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 2C swapped %d pairs of (X,Y) coordinates.\n",
			             count);
		    break;
	        case Trav3a:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 3A toggled %d dates.\n",
			             count);
		    break;
	        case Trav3b:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 3B toggled %d dates.\n",
			             count);
		    break;
	        case Trav3c:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 3C toggled %d dates.\n",
			            count);
		    break;
	        case Trav4:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 4: %d instances of the character found\n",
			             count);
		    break;
	        case Trav5do:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 5(DO): %d string replacements performed\n",
			             count);
		    break;
	        case Trav5undo:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 5(UNDO): %d string replacements performed\n",
			         count);
		    break;
	        case Trav6:
	            count = moduleH->traverse(whichOp);
	            sprintf(resultText, "Traversal 6: visited %d atomic part roots.\n",
			             count);
		    break;
	        case Trav7:
	            count = traverse7();
		    sprintf(resultText, "Traversal 7: found %d assemblies using rand om atomic part.\n", 
			count);
		    break;
	        case Trav8:
	            count = moduleH->scanManual();
		    sprintf(resultText, "Traversal 8: found %d occurrences of character in manual.\n", 
			count);
		    break;
	        case Trav9:
	            count = moduleH->firstLast();
		    sprintf(resultText, "Traversal 9: match was %d.\n", 
			count);
		    break;

                case Trav10:
                    // run traversal #1 on every module.
                    count = 0;
                    whichOp = Trav1;  // so object methods don't complain
                    for (moduleId = 1; moduleId <= TotalModules; moduleId++) {
                        sprintf(moduleName, "Module %08d", moduleId);
			bool found;
	  	        shrc rc =tbl->ModuleIdx.find(moduleName,moduleH,found);
   	                if (rc || !found ||moduleH == NULL) {
                                fprintf(stderr,
                                        "ERROR: t10 Unable to access %s.\n",
                                         moduleName);
				W_COERCE(Shore::abort_transaction());
                                exit(1);
                        }
                        count += moduleH->traverse(whichOp);
                    }
                    sprintf(resultText,
                           "Traversal 10 visited %d atomic parts in %d modules.\\n",
                                     count, TotalModules);
                    whichOp = Trav10;  // for next time around
                    break;           

	        case Query1:
	            count = query1();
	            sprintf(resultText, "Query one retrieved %d atomic parts.\n",
			             count);
		    break;
	        case Query2:
	            count = query2();
	            sprintf(resultText, "Query two retrieved %d qualifying atomic parts.\n",
			         count);
		    break;
	        case Query3:
	            count = query3();
	            sprintf(resultText, "Query three retrieved %d qualifying atomic parts.\n",
			         count);
		    break;
	        case Query4:
	            count = query4();
	            sprintf(resultText, "Query four retrieved %d (document, base assembly) pairs.\n",
			         count);
		    break;
	        case Query5:
	            count = query5();
	            sprintf(resultText, "Query five retrieved %d out-of-date base assemblies.\n",
			             count);
		    break;
	        case Query6:
	            count = query6();
	            sprintf(resultText, "Query six retrieved %d out-of-date assemblies.\n",
			         count);
		    break;
	        case Query7:
	            count = query7();
		    sprintf(resultText, "Query seven iterated through %d atomic part s.\n",
			             count);
		    break;
	        case Query8:
	            count = query8();
		    sprintf(resultText, "Query eight found %d atomic part/document m atches.\n",
			 count);
		    break;
	        case Insert:
	            insert1();
	            sprintf(resultText, "Inserted %d composite parts (a total of %d atomic parts.)\n",
		      NumNewCompParts, NumNewCompParts*NumAtomicPerComp);
		    break;
	        case Delete:
	            delete1();
	            sprintf(resultText, "Deleted %d composite parts (a total of %d atomic parts.)\n",
	             NumNewCompParts, NumNewCompParts*NumAtomicPerComp);
		    break;

		 case Reorg1:
		     count = reorg1();
		     sprintf(resultText, "Reorg1 replaced %d atomic parts.\n", 
			count);
		     break;

	    	 case Reorg2:
		     count = reorg2();
		     sprintf(resultText, "Reorg2 replaced %d atomic parts.\n", 
			count);
		     break;
// NEW
	        case WarmUpdate:
		    // first do the t1 traversal to warm the cache
	            count = moduleH->traverse(Trav1);
		    // then call T2 to do the update
	            count = moduleH->traverse(Trav2a);
	            sprintf(resultText, 
			"Warm update swapped %d pairs of (X,Y) coordinates.\n",
 			         count);
		     break;
	        default:
	            fprintf(stderr, "Sorry, that operation isn't available yet.\n");
		    // E_AbortTransaction();
		    W_COERCE(Shore::abort_transaction());
	            exit(1);
	    }
		printf("Visited=%d\n", count);
	}
	{ 
#ifdef PARSETS

	    if ((iter == repeatCount-1) || manyXACTS){
		printf("Calling commit transaction\n");
		SlaveRPC(CompNodes, (char *)slaveCommitTransaction, NULL, -1);
		choice = do_commit;
	    }
#else
	    // Commit the current transaction if 
	    // we are running the last iteration 
	    // or running a multitransaction test and not chaining
	    // Chain the tx if we are chaining and not on
	    // the last iteration

	    if (iter == repeatCount-1) {
		choice=do_commit;
		// commit 
	    } else if(manyXACTS) {
		// not last iteration, multi tx test
		if(chain_tx) {
		    choice=do_chain;
		} else {
		    choice=do_commit;
		}
	    } else choice=do_nothing;
#endif
	    if(choice==do_commit) {
		//E_CommitTransaction();
		W_COERCE(Shore::commit_transaction());
		choice = do_begin;
	    } else if (choice==do_chain) {
		W_COERCE(Shore::chain_transaction());
		choice = do_nothing;
	    } 
	}

            // compute and report wall clock time
            gettimeofday(&endWallTime, IGNOREZONE &ignoreTimeZone);
	    printf("SHORE, operation= %s, iteration= %d, elapsedTime= %f seconds\n",
               argv[opIndex], iter,
               ComputeWallClockTime(&startWallTime, &endWallTime));
            if (iter == 1) startWarmTime = startWallTime;

            // Compute and report CPU time.
	    getrusage(RUSAGE_SELF, &endUsage);
            fprintf(stdout, resultText);
	    fprintf(stdout, "CPU time: %f seconds.\n", 
	                ComputeUserTime(&startUsage, &endUsage) +
			ComputeSystemTime(&startUsage, &endUsage));
	    fprintf(stdout, "(%f seconds user, %f seconds system.)\n", 
	                ComputeUserTime(&startUsage, &endUsage),
			ComputeSystemTime(&startUsage, &endUsage));

	    if ((repeatCount > 2) && (iter == repeatCount-2)) 
	    {
	       // compute average hot time for 2nd through n-1 th iterations
               printf("SHORE, operation=%s, average hot elapsedTime=%f seconds\n",
	       	  argv[opIndex], 
	          ComputeWallClockTime(&startWarmTime, &endWallTime)/(repeatCount-2)); 
	    }
	  }

	//////////////////////////////////////////////////////////////////
	//
	// Shutdown 
	//
	//////////////////////////////////////////////////////////////////

#ifdef PARSETS
	cleanupParSets();
#endif
	// totalTime.Stop();
	// totalSrvTime.Stop();
	// fprintf(stdout, "Total stats (client,server):\n");
	// totalTime.PrintStatsHeader(stdout);
	// totalTime.PrintStats(stdout, "TotalCli");
	// totalSrvTime.PrintStats(stdout, "TotalSrv");

	// Exit
	W_COERCE(Shore::exit());
	return(0);
}
Exemple #5
0
void RecitalTabs::refreshPieces()
{
    QList<QTreeWidgetItem *> selectedItemList = ui->treeWidget->selectedItems();
    QString selectedItemIdString;
    if(!selectedItemList.empty()) {
        selectedItemIdString = selectedItemList.first()->data(0,Qt::UserRole).toString();
    }

    ui->treeWidget->clear();
    QStringList groupAlreadyDone;
    QSqlQuery query("SELECT l.lessonid, l.lessonname, pc.composer, p.title, p.genre, p.duration, pu.instrumenttype, CASE WHEN date(pu.birthday, '+' || (strftime('%Y', 'now') - strftime('%Y', pu.birthday)) || ' years') <= date('now') THEN strftime('%Y', 'now') - strftime('%Y', pu.birthday) ELSE strftime('%Y', 'now') - strftime('%Y', pu.birthday) -1 END AS age, pu.forename, pu.surname, par.parid, par.sorting FROM pupil pu, piece p, lesson l, pupilatlesson pal, piececomposer pc, pieceatrecital par WHERE pal.palid = p.palid AND p.piececomposerid=pc.piececomposerid AND pal.lessonid = l.lessonid AND pal.pupilid= pu.pupilid AND pal.stopdate > date('now') AND par.pieceid=p.pieceid AND par.ifexternalpiece=0 AND par.recitalid="+QString::number(recitalId)+" ORDER by par.sorting ASC, age ASC");
    if (query.lastError().isValid()) {
        qDebug() << "DB Error: 196 - " << query.lastError();
    }
    while(query.next()) {
        //Prüfen ob der Eintrag ein gemeinsamer Gruppeneintrag ist.
        QSqlQuery query1("SELECT count(*) FROM piece p, lesson l, pupilatlesson pal WHERE pal.palid = p.palid AND pal.lessonid = l.lessonid AND pal.stopdate > date('now') AND l.lessonid="+query.value(0).toString()+" AND p.title='"+query.value(3).toString()+"'");
        if (query1.lastError().isValid()) {
            qDebug() << "DB Error: 197 - " << query1.lastError();
        }
        query1.next();
        if(query1.value(0).toInt() > 1) {

            QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
            item->setData(1, Qt::DisplayRole, query.value(2).toString());
            item->setData(0, Qt::DisplayRole, query.value(11).toString());
            item->setData(0, Qt::UserRole, query.value(10).toString()); //set hidden parid for database actions
            item->setData(2, Qt::DisplayRole, query.value(3).toString());
            item->setData(3, Qt::DisplayRole, query.value(4).toString());
            item->setData(4, Qt::DisplayRole, query.value(5).toString()+" Min.");
//                                item->setData(4, Qt::DisplayRole, query.value(5).toString());

            QSqlQuery query2("SELECT pu.forename, pu.surname, pu.instrumenttype, CASE WHEN date(pu.birthday, '+' || (strftime('%Y', 'now') - strftime('%Y', pu.birthday)) || ' years') <= date('now') THEN strftime('%Y', 'now') - strftime('%Y', pu.birthday) ELSE strftime('%Y', 'now') - strftime('%Y', pu.birthday) -1 END AS age FROM pupil pu, pupilatlesson pal WHERE pal.pupilid= pu.pupilid AND pal.lessonid = "+query.value(0).toString()+" AND pal.stopdate > date('now') ORDER by age ASC");
            if (query2.lastError().isValid()) {
                qDebug() << "DB Error: 198 - " << query2.lastError();
            }
            QString pupilsString;
            while(query2.next()) {
                pupilsString += query2.value(1).toString()+", "+query2.value(0).toString()+" ("+query2.value(3).toString()+") - "+query2.value(2).toString()+"\n";
            }
            pupilsString = pupilsString.remove(pupilsString.length()-1,1); //remove last <br>
            item->setData(5, Qt::DisplayRole, pupilsString);

            ui->treeWidget->resizeColumnToContents(1);
            ui->treeWidget->resizeColumnToContents(2);
            ui->treeWidget->resizeColumnToContents(3);
            ui->treeWidget->resizeColumnToContents(4);
            ui->treeWidget->resizeColumnToContents(5);

        } else {
//          Einzeleintrag
            QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
            item->setData(0, Qt::DisplayRole, query.value(11).toString());
            item->setData(0, Qt::UserRole, query.value(10).toString()); //set hidden parid for database actions
            item->setData(1, Qt::DisplayRole, query.value(2).toString());
            item->setData(2, Qt::DisplayRole, query.value(3).toString());
            item->setData(3, Qt::DisplayRole, query.value(4).toString());
            item->setData(4, Qt::DisplayRole, query.value(5).toString()+" Min.");
            item->setData(5, Qt::DisplayRole, query.value(9).toString()+", "+query.value(8).toString()+" ("+query.value(7).toString()+") - "+query.value(6).toString());

            ui->treeWidget->resizeColumnToContents(1);
            ui->treeWidget->resizeColumnToContents(2);
            ui->treeWidget->resizeColumnToContents(3);
            ui->treeWidget->resizeColumnToContents(4);
            ui->treeWidget->resizeColumnToContents(5);
        }
    }

    QSqlQuery query3("SELECT par.parid, par.sorting, erp.composer, erp.title, erp.genre, erp.duration, erp.musician FROM externalrecitalpiece erp, pieceatrecital par WHERE par.pieceid=erp.erpid AND par.ifexternalpiece=1 AND par.recitalid="+QString::number(recitalId)+" ORDER by par.sorting ASC");
    if (query3.lastError().isValid()) {
        qDebug() << "DB Error: 196 - " << query3.lastError();
    }
    while(query3.next()) {

        QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
        item->setData(0, Qt::DisplayRole, query3.value(1).toString());
        item->setData(0, Qt::UserRole, query3.value(0).toString()); //set hidden parid for database actions
        item->setData(1, Qt::DisplayRole, query3.value(2).toString());
        item->setData(2, Qt::DisplayRole, query3.value(3).toString());
        item->setData(3, Qt::DisplayRole, query3.value(4).toString());
        item->setData(4, Qt::DisplayRole, query3.value(5).toString()+" Min.");
        item->setData(5, Qt::DisplayRole, query3.value(6).toString());

        ui->treeWidget->resizeColumnToContents(1);
        ui->treeWidget->resizeColumnToContents(2);
        ui->treeWidget->resizeColumnToContents(3);
        ui->treeWidget->resizeColumnToContents(4);
        ui->treeWidget->resizeColumnToContents(5);
    }

    ui->treeWidget->sortByColumn(0, Qt::AscendingOrder);

    //calculate completeDuration
    completePiecesDuration = 0;
    int piecesCounter = 0;
    QTreeWidgetItemIterator it(ui->treeWidget);
    while (*it) {
        completePiecesDuration += (*it)->data(4, Qt::DisplayRole).toString().remove(QRegExp("[^0-9]")).toInt();
        piecesCounter++;
        ++it;
    }

    if(piecesCounter) {
        completeAllInAllDuration = myConfig->readConfigInt("RecitalModerationDuration")+completePiecesDuration+(piecesCounter*myConfig->readConfigInt("RecitalBetweenPiecesDuration"));
    } else {
        completeAllInAllDuration = 0;
    }


    ui->label_completeDuration->setText("Reine Spielzeit: "+QString("<span style='color: blue;'>%1 Min.</span>").arg(completePiecesDuration)+ " - Gesch&auml;tzte Gesamtdauer: "+QString("<span style='color: blue;'>%1 Min.</span>").arg(completeAllInAllDuration));

    myCM->refreshPieceActions(ui->treeWidget->topLevelItemCount());

    //set selection
    if(ui->treeWidget->topLevelItemCount()) {
        int i;
        bool found = false;
        for (i=0; i<ui->treeWidget->topLevelItemCount(); i++) {

            QTreeWidgetItem *item = ui->treeWidget->topLevelItem(i);
            if(item->data(0, Qt::UserRole).toString() == selectedItemIdString) {
                ui->treeWidget->setCurrentItem(item);
                found = true;
                break;
            }
        }
        if(!found) {
            selectFirstItem();
        }
    }

}
// Clean the database
void SettingsTabThumbnail::doCleanDatabase() {

	if(verbose) std::clog << "thb: Clean database" << std::endl;

	QSqlQuery query(db);

	// First, we remove all entries with empty filepath (something went wrong there)
	query.prepare("DELETE FROM Thumbnails WHERE filepath=''");
	query.exec();
	query.clear();

	// Then lets look at the remaining entries
	query.prepare("SELECT * FROM Thumbnails");
	query.exec();

	// First we create a list of items that are to be deleted
	QList<QStringList> toDel;
	while(query.next()) {
		QString path = query.value(query.record().indexOf("filepath")).toString();
		int mtime = query.value(query.record().indexOf("filelastmod")).toInt();

		if(!QFile(path).exists() || mtime != int(QFileInfo(path).lastModified().toTime_t())) {

			QStringList l;
			l << path << QString("%1").arg(mtime);
			toDel << l;

		}

	}
	query.clear();

	// Then we actually delete all the items
	for(int i = 0; i < toDel.length(); ++i) {

		QSqlQuery query2(db);
		query2.prepare("DELETE FROM Thumbnails WHERE filepath=:path AND filelastmod=:mod");
		query2.bindValue(":mod",toDel.at(i).at(1));
		query2.bindValue(":path",toDel.at(i).at(0));
		query2.exec();
		if(query2.lastError().text().trimmed().length())
			std::cerr << "ERROR (del): " << query2.lastError().text().trimmed().toStdString() << std::endl;
		query2.clear();

	}

	// Error catching
	if(db.lastError().text().trimmed().length())
		std::cerr << "ERROR (after del): " << db.lastError().text().trimmed().toStdString() << std::endl;


	// Compress database
	QSqlQuery query3(db);
	query3.prepare("VACUUM");
	query3.exec();
	if(query3.lastError().text().trimmed().length())
		std::cerr << "ERROR: (Vacuum) " << query3.lastError().text().trimmed().toStdString() << std::endl;
	query3.clear();

	// Update database info
	setDatabaseInfo();

}
void Clinic2ruralcooperative::writeindb(QString strNo)
{
	sql.connect2();
	QDateTime date = QDateTime::currentDateTime();
	QSqlQuery query(*sql.db);
	QSqlQuery query2(sql.db2);
	QSqlQuery query3(sql.db2);
	QSqlQuery query4(*sql.db);
	QString strsheetNo;

	query2.prepare("delete from HIS.t_con3 where Mzlsh = '"+strNo+"'");
	query2.exec();
	query2.prepare("delete from HIS.t_con4 where Mzlsh = '"+strNo+"'");
	query2.exec();

	query.exec("select * from mz_chargesheet where sheetno= '"+strNo+"'");
	while(query.next())
	{
		strsheetNo=query.value(1).toString();
		QString strpatient=query.value(5).toString();
		QString strgender=query.value(6).toString();
		QString strID=query.value(11).toString();
		QString strsheetmaker=query.value(15).toString();
		query2.prepare("insert into HIS.t_con3 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
		query2.bindValue(0, strsheetNo);
		query2.bindValue(1,strsheetNo);
		query2.bindValue(2,query.value(12).toString());
		query2.bindValue(3, strpatient);
		if (strgender==QString::fromLocal8Bit("男"))
		{
			query2.bindValue(4, 1);
		}
		if (strgender==QString::fromLocal8Bit("女"))
		{
			query2.bindValue(4, 2);
		}

		query2.bindValue(5, strID);
		query2.bindValue(6,NULL);
		query2.bindValue(7, query.value(2).toDateTime());
		query2.bindValue(8, strsheetmaker);
		query2.bindValue(9, 1);
		query2.bindValue(10, NULL);
		query2.bindValue(11, NULL);
		query2.bindValue(12, NULL);
		query2.bindValue(13, NULL);
		query2.bindValue(14,NULL);
		query2.bindValue(15,NULL);
		query2.bindValue(16, NULL);
		query2.bindValue(17, NULL);
		query2.bindValue(18, NULL);
		query2.bindValue(19, NULL);
		query2.bindValue(20, NULL);
		query2.bindValue(21, NULL);
		query2.bindValue(22, NULL);
		if(query2.exec())
		{

//			QMessageBox::information(this,QString ::fromLocal8Bit("提示"),QString::fromLocal8Bit("保存成功!"));
		}

		int count=0;
		query2.exec("select * from HIS.t_con4");
		while(query2.next())
		{
			count++;
		}

		query4.exec("select * from mz_chargedetail where sheetno= '"+strsheetNo+"'");
		while(query4.next())
		{
			count++;
			query3.prepare("insert into HIS.t_con4 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
			query3.bindValue(0, count);
			query3.bindValue(1, NULL);
			query3.bindValue(2,query4.value(1).toString());
			query3.bindValue(3, query4.value(9).toDateTime());
			query3.bindValue(4, NULL);

			int drugflag = query.value(10).toInt();

			query3.bindValue(5,drugflag);//医药分类
			query3.bindValue(6,NULL);
			query3.bindValue(8,NULL);
			QString strdrug =query4.value(4).toString();
			if (drugflag==1)
			{
				QSqlQuery query5(*sql.db);	

				query5.exec("select * from sys_drugcorrespondence where yymc= '"+strdrug+"'");
				while (query5.next())
				{
					query3.bindValue(6, query5.value(1).toString());
					query3.bindValue(7, query5.value(3).toString());
					query3.bindValue(8, query5.value(2).toString());
					query3.bindValue(9, query5.value(4).toString());

					query3.bindValue(20, NULL);//医疗项目分类
				}
			}
			if (drugflag==2)
			{
				QSqlQuery query5(*sql.db);	
				QString strdrugtype,nhcode,nhname,hiscode,hisname;
				query5.exec("select * from sys_projectcorrespondence where yymc= '"+strdrug+"'");
				while (query4.next())
				{
					query3.bindValue(6, query5.value(1).toString());
					query3.bindValue(7, query5.value(3).toString());
					query3.bindValue(8, query5.value(2).toString());
					query3.bindValue(9, query5.value(4).toString());
					query3.bindValue(20, query5.value(7).toString());//医疗项目分类
				}
			}
			if (drugflag==3)
			{
				QSqlQuery query5(*sql.db);	
				QString strdrugtype,nhcode,nhname,hiscode,hisname;
				query5.exec("select * from sys_materialcorrespondence where yymc= '"+strdrug+"'");
				while (query4.next())
				{
					query3.bindValue(6, query5.value(1).toString());
					query3.bindValue(7, query5.value(3).toString());
					query3.bindValue(8, query5.value(2).toString());
					query3.bindValue(9, query5.value(4).toString());
					query3.bindValue(20, NULL);//医疗项目分类
				}
			}

			//query3.bindValue(6, 6);
			//query3.bindValue(7, 7);
			//query3.bindValue(8,"8");
			//query3.bindValue(9, "9");

			query3.bindValue(10, query4.value(6).toDouble());
			query3.bindValue(11,query4.value(7).toDouble());
			query3.bindValue(12, query4.value(8).toDouble());

			QSqlQuery query5(*sql.db);	
			query5.exec("select * from sys_drugdictionary where name= '"+query4.value(4).toString()+"'");
			while (query5.next())
			{
				QString strdrugtype = query5.value(14).toString();
				if (strdrugtype==QString::fromLocal8Bit("西药"))
				{
					query3.bindValue(13, 1);
				}
				else if (strdrugtype==QString::fromLocal8Bit("中成药"))
				{
					query3.bindValue(13, 2);
				}
				else if (strdrugtype==QString::fromLocal8Bit("中草药"))
				{
					query3.bindValue(13, 3);
				}
			}
			query3.bindValue(14,1);//药品属性
			query3.bindValue(15, NULL);
			query3.bindValue(16, NULL);
			query3.bindValue(17,NULL);
			query3.bindValue(18, NULL);
			query3.bindValue(19,NULL);
			query3.bindValue(20,NULL);
			//医疗项目的财务分类

			query3.bindValue(21,NULL);
			query3.bindValue(22, NULL);
			query3.bindValue(23,NULL);
			query3.bindValue(24, NULL);
			query3.bindValue(25, NULL);
			query3.bindValue(26,NULL);
			query3.bindValue(27, NULL);
			query3.bindValue(28, NULL);
			query3.bindValue(29,NULL);
			query3.bindValue(30, NULL);
			query3.bindValue(31, NULL);
			query3.exec();

		}
//		QMessageBox::information(this,QString ::fromLocal8Bit("提示"),QString::fromLocal8Bit("保存成功!"));
		query4.prepare("update mz_chargesheet set out2cooperativeflag= ? where sheetno= '"+strsheetNo+"'");
		query4.bindValue(0,1);
		query4.exec();
	}
	sql.disconnect2();
}
void CreateBooking::on_saveBookingBtn_clicked()
{

    QMessageBox msgBox;
    //int room_id = ui->roomsList->currentData().toInt();
    //ui->customer_name->completer()->currentIndex()
    //int customer_id = ui->c_customer_name->completer()->currentIndex().data(Qt::UserRole).toInt();
    int customer_id = m_customer_id;
    //customer_id = ui->c_customer_name->completer()->currentIndex().data(Qt::UserRole).toInt();
    /*
    QModelIndex index = ui->c_customer_name->completer()->currentIndex();
    if (index.isValid()) {
        int row = index.row();
        customer_id =  ui->c_customer_name->completer->completionModel()->index(row, 0).data().toInt();
        //qDebug() << key;
    }
    */
    if(customer_id < 0)
    {
        msgBox.warning(this,"Save Booking","Wrong customer details.");
        return;
    }

    qDebug()<<"Customer Id:"<<customer_id;
    QDate booking_date_from = ui->from_date->date();
    QDate booking_date_to = ui->to_date->date();

    if(ui->room_status_table->rowCount() <= 0 )
    {
        msgBox.warning(this,"Save Booking","Please check the availability of rooms before saving the booking.");
        return;
    }

    if(!this->checkRoomAvailability())
    {
        //msgBox.warning(this,"Save Booking","Please check the availability of rooms before saving the booking.");
        return;
    }




    int customer_status = ui->customer_status->currentData().toInt();
    int num_of_persons = ui->num_of_person->text().toInt();
    int booking_status = ui->booking_status->currentData().toInt();
    QString name_of_persons = ui->persons_name->toPlainText();
    QString comments = ui->comments->toPlainText();
    int payment_status  = ui->payment_status->currentData().toInt();

    QString check_in_time;
    if(customer_status == 2)
    {
        check_in_time = ui->check_in_date_time->dateTime().toString("yyyy-MM-dd hh:mm:ss");
    }

    DbMysql* d = DbMysql::getInstance();

    if(!d->getConnection().open())
    {
        msgBox.critical(this,"Error","Failed to connect database.1");
    }
    else
    {
        int booking_id = 0;
        if(mEditMode)
        {
            booking_id=mBookingId;
        }
        else
            booking_id = this->genBookingId();


        //QSqlQuery query2("INSERT INTO `room_booking` VALUES (DEFAULT, '"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"', '"+QString::number(customer_id)+"', '"+booking_date_from.toString("yyyy-MM-dd")+"', '"+booking_date_to.toString("yyyy-MM-dd")+"', '"+QString::number(room_id)+"', '"+QString::number(booking_status)+"', '"+QString::number(customer_status)+"', '"+QString::number(payment_status)+"', '"+QString::number(num_of_persons)+"','"+name_of_persons+"','"+comments+"');",d->getConnection());


        QString sql0;

        if(mEditMode)
        {
            sql0 = "UPDATE `booking` set customer_id="+QString::number(customer_id)+",booking_from='"+booking_date_from.toString("yyyy-MM-dd")+"',booking_to='"+booking_date_to.toString("yyyy-MM-dd")+"',booking_status="+QString::number(booking_status)+", customer_status='"+QString::number(customer_status)+"',nop='"+QString::number(num_of_persons)+"',persons_name='"+name_of_persons+"',commnets='"+comments+"' where booking_id="+QString::number(mBookingId)+";";
        }
        else
        {
            sql0 = "INSERT INTO `booking` VALUES (DEFAULT, '"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"', '"+QString::number(customer_id)+"', '"+booking_date_from.toString("yyyy-MM-dd")+"', '"+booking_date_to.toString("yyyy-MM-dd")+"','"+((check_in_time.length() > 0)?check_in_time:"NULL")+"','NULL','',"+QString::number(booking_status)+", '"+QString::number(customer_status)+"', '"+QString::number(payment_status)+"', '"+QString::number(num_of_persons)+"','"+name_of_persons+"','"+comments+"');";
        }

        QSqlQuery query1(sql0,d->getConnection());
        if(query1.isActive())
        {
            if(mEditMode)
            {
                QSqlQuery query11("delete from room_bookings where booking_id="+QString::number(mBookingId)+";",d->getConnection());
                if(!query11.isActive())
                {
                    qDebug()<<query11.lastQuery();
                }
            }


            QString sql = "Insert into room_bookings values ";


            QString sql2 = "Update rooms set room_state=1 where room_id in (";

            bool comaFlag = false;

            QList<QListWidgetItem*> room_items =  ui->room_list->selectedItems();
            ui->room_status_table->setRowCount(room_items.size());
            int row = 0;
            foreach (QListWidgetItem* item, room_items)
            {
                if(comaFlag)sql+=",";
                sql += "(DEFAULT,"+ui->room_status_table->item(row,1)->text()+","+item->data(Qt::UserRole).toString()+",'"+booking_date_from.toString("yyyy-MM-dd")+"', '"+((ui->single_day->isChecked())?booking_date_from.toString("yyyy-MM-dd"):booking_date_to.toString("yyyy-MM-dd"))+"',"+QString::number(booking_id)+")";
                sql2 += item->data(Qt::UserRole).toString();
                comaFlag = true;
                row++;
            }

            sql2+= ");";

            if(!mEditMode)
            {
                if(check_in_time.length() > 0)
                {
                    QSqlQuery query3(sql2,d->getConnection());
                }
            }

            if(ui->payment_status->currentData(Qt::UserRole).toInt() == 3)
            {

                QSqlQuery query4("insert into advance_payments values (DEFAULT,"+ui->advanceMoney->text()+","+QString::number(booking_id)+",NOW());",d->getConnection());
                if(!query4.isActive())
                {
                    qDebug()<<query4.lastQuery();
                    qDebug()<<query4.lastError();
                    return;
                }
            }


            QSqlQuery query2(sql,d->getConnection());
            if(query2.isActive())
            {
                if(mEditMode)
                {
                    msgBox.information(this,"Edit Booking","Update Booking done.");
                }
                else
                {
                    msgBox.information(this,"Booking","Booking done.");
                }

                this->mpParent->populateBookingLog();
                this->mpParent->createCalendar();

                this->close();
            }
            else
            {
                qDebug()<<query2.lastQuery();
                qDebug()<<query2.lastError();
                return;
            }



        }
        else
        {
            qDebug()<<query1.lastQuery();
            qDebug()<<query1.lastError();
            return;
        }

    }
void CreateBooking::setEditMode(bool mode)
{
    this->mEditMode = true;

    this->setWindowTitle("Edit Booking");

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

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

        QSqlQuery query1( "select * from booking_details where booking_id="+QString::number(this->mBookingId)+";" ,d->getConnection());
        QSqlQuery query2( "select * from booking where booking_id="+QString::number(this->mBookingId)+";" ,d->getConnection());
        QSqlQuery query3( "SELECT room_bookings.*,rooms.room_number FROM `room_bookings`left join rooms on rooms.room_id = room_bookings.room_id where booking_id="+QString::number(this->mBookingId)+";" ,d->getConnection());
        if((!query1.isActive() || !query2.isActive()) || !query3.isActive())
        {
            msgBox.critical(this,"Error","Failed to connect database.");
        }
        else
        {
            query1.next();
            query2.next();
            if(query1.value("booking_from").toDate() == query1.value("booking_to").toDate())
            {
                ui->single_day->setChecked(true);
            }
            else
            {
                ui->multiple_day->setChecked(true);
                ui->to_date->setDisabled(false);
            }

            mBookingFrom = query1.value("booking_from").toDate();
            mBookingTo = query1.value("booking_to").toDate();

            ui->from_date->setDate(query1.value("booking_from").toDate());
            ui->to_date->setDate(query1.value("booking_to").toDate());

            ui->c_customer_name->setText(query1.value("customer_name").toString());
            //ui->c_customer_name->completer()->setCurrentRow();
            QStandardItemModel* md = (QStandardItemModel*)ui->c_customer_name->completer()->model();
            qDebug() <<md->rowCount();
            QModelIndexList ml = md->match(md->index(0,0),Qt::UserRole,QVariant::fromValue(query2.value("customer_id").toInt()));

            if(ml.size() > 0)
            {
                ui->c_customer_name->completer()->activated(ml.at(0));
            }

            ui->customer_status->setCurrentIndex(query2.value("customer_status").toInt()-1);
            ui->check_in_date_time->setDateTime(query2.value("in_time").toDateTime());
            ui->num_of_person->setText(query2.value("nop").toString());
            ui->persons_name->setPlainText(query2.value("persons_name").toString());
            ui->comments->setPlainText(query2.value("commnets").toString());

            int i = 0;

            ui->room_status_table->setRowCount(query3.size());

            while(query3.next())
            {
                QTableWidgetItem* tItem  = new QTableWidgetItem();
                tItem->setText(query3.value("room_number").toString());
                tItem->setFlags(tItem->flags() & ~Qt::ItemIsEditable);

                QTableWidgetItem* tItem1  = new QTableWidgetItem();
                tItem1->setText(QString::number(query3.value("room_rate").toDouble(),'f',2));


                QTableWidgetItem* tItem2  = new QTableWidgetItem();
                tItem2->setText(query3.value("booking_from").toString());
                tItem2->setFlags(tItem2->flags() & ~Qt::ItemIsEditable);

                QTableWidgetItem* tItem3  = new QTableWidgetItem();
                if(ui->single_day->isChecked())
                {
                    tItem3->setText("");
                }
                if(ui->multiple_day->isChecked())
                {
                    tItem3->setText(query3.value("booking_to").toString());
                }

                tItem3->setFlags(tItem3->flags() & ~Qt::ItemIsEditable);


                QTableWidgetItem* tItem4  = new QTableWidgetItem();
                tItem4->setText("Available");
                tItem4->setFlags(tItem4->flags() & ~Qt::ItemIsEditable);

                ui->room_status_table->setItem(i,0,tItem);
                ui->room_status_table->setItem(i,1,tItem1);
                ui->room_status_table->setItem(i,2,tItem2);
                ui->room_status_table->setItem(i,3,tItem3);
                ui->room_status_table->setItem(i,4,tItem4);
                i++;

                for(int j= 0 ;j<ui->room_list->count();j++)
                {
                    if(ui->room_list->item(j)->data(Qt::UserRole).toInt() == query3.value("room_id").toInt())
                    {
                        ui->room_list->item(j)->setSelected(true);
                    }
                }


            }
            ui->advPayGBox->setVisible(false);
            ui->room_status_table->resizeColumnsToContents();


        }
    }
}
Exemple #10
0
int main (){
	int i, num = 1, lido=0;
	
	for(i = 0; i < 12; i++){
		contas[i] = NULL;
		compras[i] = NULL;
	}
    
    while(num > 0 && num < 15){
    	system("clear");
   		carregaTextArt("textart-big.txt");
   		puts("\n");
   		num = menuOpcoes();
    	printf("Opção: %d\n",num);
    	switch(num){
    		case 1: {
    			if(lido){
    				for(i = 0; i < 12; i++){
						contas[i] = NULL;
						compras[i] = NULL;
					}
					for(i = 0; i < 26; i++){
						clientes[i] = NULL;
						produtos[i] = NULL;
					}
    			}
                query1(); 
                lido=1; 
                break;
            }    
			case 2: {
                if(lido) query2();
            } break;        
			case 3: {
                if(lido) query3();
            } break;
			case 4: {
                if(lido) query4();
            } break;
                
            case 5: {
                if(lido) query5();
            } break;
                
			case 6: {
                if(lido) query6();
            } break;
                
            case 7: {
                if(lido) query7();
            } break;
                
            case 8: {
                if(lido) query8();
            } break;
                
            case 9: {
                if(lido) query9();
            } break;

            case 10: {
                if(lido) query10();
            } break;

            case 11: {
                if(lido) query11();
            } break;
                
            case 12: {
                if(lido) query12();
            } break;
                
            case 13: {
                if(lido) query13();
            } break;
              
            case 14: {
                if(lido) query14();
            } break;
    	}
    }

    return 0;
}