void staff() { int choice = 0; while (1) { if (choice >= 0 && choice <= 7) { CLRSCR(); //clears window up until this point puts("-------------------------------------------------------"); puts("1. Make a booking"); puts("2. Complete a booking"); puts("3. Search for available tables by no. of seats"); puts("4. Display menu and take order"); puts("5. Display receipt"); puts("6. Show information on tables"); puts("7. Show future bookings"); puts("0. Exit"); printf("-------------------------------------------------------"); } choice = onlyInt(1); switch (choice){ case 0: return; case 1: staffAddBooking(); break; //make a booking case 2: completeBooking(); break; //complete booking case 3: showAvailableTables(); break; case 4: selectTable(1); break; //display menu function case 5: selectTable(2); break; //display receipt function case 6: showAllTables(); break; case 7: showFutureBookings(); break; default: printf("That is not one of the options!\nPlease enter again: "); } } }
int main() { printf("\n"); selectTable(6, 5, 2); printf("\n"); selectTable(5, 4, 3); printf("\n"); selectTable(2, 4, 7); printf("\n"); selectTable(10, 3, 1); return 0; }
void administrator() { int choice = 0; int password; //check to see if password entered correctly, 0 for incorrect, 1 for correct //Password: Password1! //key: 1234 puts("Please enter the administrator password. 3 attempts remaining:"); password = checkPassword(); if (password == 0) { puts("Password and Key combination incorrectly entered 3 times.\nProgram is exiting..."); return; } while (1) { if (choice >= 0 && choice <= 11) { CLRSCR(); //clears window up until this point puts("-------------------------------------------------------"); puts("1. Make/Edit/Delete a booking"); puts("2. Complete a booking"); puts("3. Search for available tables by no. of seats"); puts("4. Display menu and take order"); puts("5. Display receipt"); puts("6. Show information on tables"); puts("7. Show future bookings"); puts("8. Edit Tables"); puts("9. Edit Menu"); puts("10. Change Administrator password"); puts("0. Exit"); printf("-------------------------------------------------------"); } choice = onlyInt(2); switch (choice){ case 0: return; case 1: editBooking(); break; //make a booking case 2: completeBooking(); break; //complete booking case 3: showAvailableTables(); break; case 4: selectTable(1); break; //display menu function case 5: selectTable(2); break; //display receipt function case 6: showAllTables(); break; case 7: showFutureBookings(); break; case 8: editTables(); break; case 9: editMenu(); break; //edit menu.dat file case 10: changePassword(); return; //program logs user out after changing password default: printf("That is not one of the options!\nPlease enter again: "); } } }
void CWTOscillator::update() { COscillator::update(); // --- calculate the inc value m_dWT_inc = WT_LENGTH*m_dInc; // --- select the table selectTable(); }
void HighScore::loadTables() { char buff[1024]; // open the file, on error set up the default table FILE *fp = fopen( QFile::encodeName(highScoreFile()), "r"); if (fp == NULL) goto error; // check magic fscanf(fp, "%1023s\n", buff); if (highScoreMagic1_1 != buff) { goto error; } int num; fscanf(fp, "%d\n", &num); for (int p=0; p<num; p++) { TableInstance *t = new TableInstance; t->next = tables; tables = t; fgets(buff, sizeof(buff), fp); if (buff[strlen(buff)-1] == '\n') buff[strlen(buff)-1] = '\0'; t->name = buff; combo->insertItem(t->name); setComboTo(t->name); for (int e=0; e<numScores; e++) { fscanf(fp, "%ld\n", &(t->entries[e].score)); fscanf(fp, "%ld\n", &(t->entries[e].elapsed)); fscanf(fp, "%ld\n", &(t->entries[e].board)); fgets(buff, sizeof(buff), fp); if (buff[strlen(buff)-1] == '\n') buff[strlen(buff)-1] = '\0'; t->entries[e].name=QString::fromUtf8(buff,-1); } } fclose(fp); return; error: selectTable("default"); saveTables(); return; }
void HighScore::checkHighScore(int s, int e, long gameNum, QString &name) { int pos; QString board; getBoardName(name, board); // make this board name the current one! // creates it if it does not exist selectTable(board); for (pos=0; pos <numScores; pos++) { if (s > currTable->entries[pos].score) { break; } } if (pos >= numScores) { return; } for (int move= numScores-1; move >pos; move--) { currTable->entries[move].score = currTable->entries[move-1].score; currTable->entries[move].name = currTable->entries[move-1].name; currTable->entries[move].board = currTable->entries[move-1].board; currTable->entries[move].elapsed = currTable->entries[move-1].elapsed; } currTable->entries[pos].score = s; currTable->entries[pos].board = gameNum; currTable->entries[pos].elapsed = e; lineEdit->setEnabled(true); lineEdit->setGeometry( 40, 75+(pos*30), 150, 30 ); lineEdit->setFocus(); lineEdit->setText(""); selectedLine = pos; nameChanged(""); // no board change when entering data combo->setEnabled(false); exec(board); combo->setEnabled(true); selectedLine = -1; lineEdit->setGeometry( 40, 75+(20*30), 150, 30); lineEdit->setEnabled(false); // sync the hiscore table to disk now saveTables(); }
void SociContainer::setSelector(StdString const &oId) { Progress prg("Loading from Table ..."); if(oId.length() > 0 && oId[0] == '{') // If it is a table we select it { mTablename = oId.substr(1, oId.length()-2); selectTable(mTablename, false); } else mTablename = ""; super::setSelector(oId); refreshPreview(selectorToQuery(), mPreviewLimit); }
void HighScore::reset() { int res=KMessageBox::warningContinueCancel(this, i18n("Resetting the high scores will " "remove all high score entries " "both in memory and on disk. Do " "you wish to proceed?"), i18n("Reset High Scores"),i18n("Reset")); if (res != KMessageBox::Continue) return ; // delete the file res = unlink( QFile::encodeName(highScoreFile())); // wipe ou the in memory list of tables TableInstance *t, *d; if (tables != NULL) { t = tables; while (t != NULL) { d = t; t = t->next; d->next=0; delete d; } } // set the list empty tables = NULL; currTable=NULL; // clear out the combobox combo->clear(); // stick in a default selectTable("default"); // make sure tha the on screen data does not // point to deleted data copyTableToScreen("default"); }
void HighScore::copyTableToScreen(const QString &name) { char buff[256]; QString base; getBoardName(name, base); selectTable(base); for (int p=0; p<numScores;p++) { scoresWidgets[p]->setNum((int)currTable->entries[p].score); namesWidgets[p]->setText(currTable->entries[p].name); boardWidgets[p]->setNum((int)currTable->entries[p].board); int e = currTable->entries[p].elapsed; int s = e % 60; e = e-s; int m = (e % (60*60)) / 60; e = e - (e % (60*60)); int h = (e % (60*60*60)) / (60*60); sprintf(buff, "%2.2d:%2.2d:%2.2d", h, m , s); elapsedWidgets[p]->setText(buff); } repaint(false); }
bool AddConstraintHandler::handleURI(URI& uri) { if (uri.action != "add_constraint") return false; wxString type = uri.getParam("type"); // pk, fk, check, unique Table* t = extractMetadataItemFromURI<Table>(uri); wxWindow* w = getParentWindow(uri); if (!t || !w) return true; // Find first available constraint name: DatabasePtr db = t->getDatabase(); wxString prefix = type + "_" + t->getName_(); wxString stmt( "select rdb$constraint_name from rdb$relation_constraints " "where rdb$relation_name = '" + t->getName_() + "' and rdb$constraint_name starting with '" + prefix + "' order by 1"); wxString default_value; wxArrayString constraintNames(db->loadIdentifiers(stmt)); for (int i = 0; ; ++i) { default_value = prefix + wxString::Format("_%d", i); if (constraintNames.Index(default_value, false) == wxNOT_FOUND) break; } wxString cname = ::wxGetTextFromUser(_("Enter constraint name"), _("Adding new table constraint"), default_value, w); if (cname.IsEmpty()) // cancel return true; wxString sql = "alter table " + t->getQuotedName() + "\nadd constraint " + Identifier::userString(cname); if (type == "PK") { wxString columnlist = selectRelationColumns(t, w); if (columnlist.IsEmpty()) // cancel return true; sql += "\nprimary key (" + columnlist + ")"; } else if (type == "FK") { wxString columnlist = selectRelationColumns(t, w); if (columnlist == "") return true; TablePtr ref = selectTable(t->getDatabase(), w); if (!ref) return true; wxString refcolumnlist = selectRelationColumns(ref.get(), w); if (refcolumnlist == "") return true; sql += "\nforeign key (" + columnlist + ") \nreferences " + ref->getQuotedName() + " (" + refcolumnlist + ")"; wxString action = selectAction(_("update"), w); if (action == "CANCEL") return true; else if (action != "RESTRICT") sql += "\non update " + action + " "; action = selectAction(_("delete"), w); if (action == "CANCEL") return true; else if (action != "RESTRICT") sql += "\non delete " + action + " "; } else if (type == "CHK") { wxString source; if (!GetMultilineTextFromUser(w, _("Enter check condition"), source)) return true; sql += "\ncheck (" + source + ")"; } else if (type == "UNQ") { wxString columnlist = selectRelationColumns(t, w); if (columnlist.IsEmpty()) // cancel return true; sql += "\nunique (" + columnlist + ")"; } else { ::wxMessageBox(_("Unknown constraint type"), _("Error."), wxOK | wxICON_ERROR); return true; } execSql(w, "", db, sql, true); // true = commit + close at once return true; }
void shell() { current_database = -1; char entrada[1000], nomeBD[TAM_NOME_BANCO]; int resultado = 0, codDB = -1; nomeBD[0]='\0'; char *current_db_name = strdup(">");//inicializa com nenhum banco conectado char *start; start = strdup("dbms-start");//este comando posteriormente como start do banco, no momento ele é automatico printf("\nWelcome to the DBMS Interface.\nType 'help' '\\h' for help.\n\n"); /** * **************************** * * Comandos do shell * * **************************** */ using_history ();//função para usar o histórico read_history (".history_file"); while(1) { int nTokens; strcpy(entrada, readline(current_db_name)); /** * Adiciona ao histórico */ if (entrada[0]) { char *expansion; int result; result = history_expand (entrada, &expansion); if (result) fprintf (stderr, "%s", expansion); if (result < 0 || result == 2) { free (expansion); continue; } add_history (expansion); strncpy (entrada, expansion, sizeof (entrada) - 1); free (expansion); write_history (".history_file");//adiciona no histórico } char **tokens = tokenize( trim_white_space(remove_newline(entrada)),' ',&nTokens); /** * Opção para criar tabela e banco de dados */ if (strcmp(strtolower(tokens[0]),"create")==0) { if(strcmp(strtolower(tokens[1]),"table")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } createTable(entrada,current_database); } else if(strcmp(strtolower(tokens[1]),"database")==0) { if (nTokens >= 5) { printf("Invalid command. Type help to show de interface usage.\n"); continue; } if (strlen(tokens[2]) > TAM_NOME_BANCO ) { printf("Database name too big.\n"); continue; } resultado = checkCreateDB( remove_semicolon(tokens[2]) );//verifica a existência do nome e grava-o no arquivo if(resultado==-1) { printf("Error creating database file.\n"); } if(resultado==-3) { printf("Database exists.\n"); } else { printf("Database created successfully.\n"); } } else { printf("Invalid command. Type help to show de interface usage.\n"); continue; } } /** * Conecta ao banco de dados passado como parâmetro */ else if(strcmp(strtolower(tokens[0]),"\\c") == 0){ if (nTokens != 2) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } char *name_db = remove_semicolon(tokens[1]); codDB = busca(name_db,1); //função chamada para conecção no banco, retorna o codigo do banco ao conectar if (codDB >= 0) { strcpy(nomeBD, name_db); //passa o nome do bd, para a variavel mostrar ao usuario qual o banco conectado free(current_db_name); current_db_name = (char*) malloc (sizeof(char)*(strlen(name_db)+3)); if (current_db_name == NULL) { printf("Out of memory.\nAborting...\n"); } strcpy(current_db_name,name_db); current_database = codDB; strcat(current_db_name,"=#"); current_db_name[strlen(current_db_name)] = '\0'; } else { printf("No such database '%s'.\n", name_db); continue; } } /** * Insere tuplas em uma tabela */ else if(strcmp(strtolower(tokens[0]),"insert")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } insert(entrada,current_database); } /** * Imprime as tabelas do banco de dados atual * ou o esquema de uma tabela */ else if(strcmp(strtolower(tokens[0]),"\\d")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } if (nTokens >= 3) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } else if (nTokens == 1) { //imprime tabelas do banco de dados listaTabelas(current_database); } else { //imprime o esquema de uma tabela char *t = table_name_real(remove_semicolon(tokens[1]),current_database); if(!verificaNomeTabela(t)){ printf("Invalid table name.\n"); free(t); continue; } struct fs_objects objeto = leObjeto(t);//para verificar se a tabela esta no banco show_schema(objeto,tokens[1]); free(t); } } /** * Comando temporário para imprimir tabela */ else if (strcmp(strtolower(tokens[0]),"select")==0) { if (current_database == -1) { printf("Not connected to any database.\n"); continue; } selectTable(entrada,current_database); } /** * Imprime os registros da tabela passada */ else if (strcmp(strtolower(tokens[0]),"show")==0) { if (nTokens != 2) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } if (current_database == -1) { printf("Not connected to any database.\n"); continue; } if (verificaNomeTabela(table_name_real(remove_semicolon(tokens[1]),current_database) ) == 0 ) { printf("Table %s doesn't exist.\n",remove_semicolon(tokens[1])); continue; } char *t = table_name_real(remove_semicolon(tokens[1]),current_database); char *file = table_name_real(remove_semicolon(tokens[1]),current_database); strcat(file,".dat"); if (existeArquivo(file) == 0) { printf("Table is empty.\n" ); continue; } imprime(t); free(file); free(t); } /** * Lista os bancos existentes */ else if(strcmp(strtolower(tokens[0]),"\\l")==0) { if (nTokens != 1) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } //LISTA os bancos existentes listaBancos(); } /** * Opção para deletar o banco de dados e tabelas */ else if(strcmp(strtolower(tokens[0]),"drop")==0) { if (nTokens != 3) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); continue; } else if(strcmp(strtolower(tokens[1]),"table") == 0){ if (current_database == -1) { printf("Not connected to any database.\n"); continue; } if (verificaNomeTabela(table_name_real(remove_semicolon(tokens[2]),current_database) ) == 0 ) { printf("Table %s doesn't exist.\n",remove_semicolon(tokens[2])); continue; } char *t = table_name_real(remove_semicolon(tokens[2]),current_database); char *exist = table_name_real(remove_semicolon(tokens[2]),current_database); int ok = excluirTabela(t); if (ok == SUCCESS) { printf("Table deleted successfully.\n"); } free(exist); free(t); } else if(strcmp(strtolower(tokens[1]),"database") == 0){ char *exist = table_name_real(remove_semicolon(tokens[2]),current_database); strcat(exist,".dat"); if (existeArquivo(exist) != 0) { printf("The database is not empty for drop, there are existing tables.\n" ); continue; } exist = remove_semicolon(tokens[2]); codDB = busca(exist,1); if(codDB == current_database) { printf("Cannot drop the currently open database.\n"); continue; } int drop = dropDatabase(remove_semicolon(tokens[2])); if(drop == 1)printf("Database deleted successfully.\n"); free(exist); } } /** * Ajuda ao usuário com exemplos da sintaxe dos comandos */ else if (strcmp(strtolower(tokens[0]),"help")==0 || strcmp(strtolower(tokens[0]),"\\h")==0) { if (nTokens != 1) { printf("Invalid number of arguments. Type help to show the interface usage.\n"); } help(); } /** * Imprime mensagem de copyright */ else if(strcmp(strtolower(remove_semicolon(tokens[0])),"\\copyright")==0) { printf("\nDatabase Management System\n"); printf("\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose, without fee, and without a written agreement\nis hereby granted, provided that the above copyright notice and this\nparagraph and the following two paragraphs appear in all copies.\n"); printf("\nTHIS SOFTWARE IS BEING DEVELOPED BY STUDENTS OF DATABASE II CLASS AT UNIVERSIDADE FEDERAL DA FRONTEIRA SUL.\n\n"); } /** * Comando de saída */ else if(strcmp(strtolower(remove_semicolon(tokens[0])),"exit")==0) { break; } else if(strcmp(strtolower(remove_semicolon(tokens[0])),"quit")==0) { break; } else if(strcmp(strtolower(remove_semicolon(tokens[0])),"bye")==0) { break; } else if(strcmp(strtolower(remove_semicolon(tokens[0])),"\\q")==0) { break; } else { printf("Invalid command. Type help to show the interface usage.\n"); continue; } } free(start); free(current_db_name); }
// insert operation. bool insertRecord(sql::Connection *con) { string cid, first_name, last_name, address, phone; string food_name, category, stmtstr; int age, calorie, quantity; string prompt = "Please select the table you want to insert into:"; sql::Statement *stmt; char tbl = selectTable(prompt); switch(tbl) { case 'c': { // insert to Customer table. cout << "You have selected Customer table. " << endl; cout << "Please provide customer information: " << endl; cout << "Please enter a customer id(string): "; cin >> cid; cout << "Please enter first name(string): "; cin >> first_name; cout << "Please enter last name(string): "; cin >> last_name; cout << "Please enter age(int): "; cin >> age; cout << "Please enter address(string): "; cin >> address; cout << "Please enter phone number(string): "; cin >> phone; try { stmt = con->createStatement(); stmtstr = "INSERT INTO Customer(CID, CFname, CLname, CAddress, CAge, CPhone) \ VALUES(\""+cid+"\",\""+first_name+"\",\""+last_name+"\",\"" \ +address+"\",\""+itoa(age)+"\",\""+phone+"\")"; stmt->execute(stmtstr); con->commit(); cout << endl << first_name << ", thanks for registration. " << endl; stmt->close(); } catch(sql::SQLException &e) { cout << "# ERROR: SQLException in " << __FILE__; cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl; cout << "# ERROR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } break; } case 'f': { // insert to Food table. cout << "You have selected Food table." << endl; cout << "Please enter food name(string): "; cin >> food_name; cout << "Please enter food Category(string): "; cin >> category; cout << "Please enter unit calorie(int): "; cin >> calorie; try { stmt = con->createStatement(); stmtstr = "INSERT INTO Food(FName, FCategory, FUcalorie) \ VALUES(\""+food_name+"\",\""+category+"\",\""+itoa(calorie)+"\")"; stmt->execute(stmtstr); con->commit(); cout << food_name << " is successfully registrated! " << endl; stmt->close(); } catch(sql::SQLException &e) { cout << "# ERROR: SQLException in " << __FILE__; cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl; cout << "# ERROR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } break; } case 'o': { // insert to FOrder table. cout << "You have selected Order table. " << endl; cout << "Please enter customer id(string): "; cin >> cid; cout << "Please enter food name(string) you want to order: "; cin >> food_name; cout << "Please enter quantity(int): "; cin >> quantity; try { stmt = con->createStatement(); stmtstr = "INSERT INTO FOrder (OCID, OFName, OQuant)\ VALUES(\""+cid+"\",\""+food_name+"\",\""+itoa(quantity)+"\")"; stmt->execute(stmtstr); con->commit(); cout << "Order successfully placed, thanks for your business!" << endl; stmt->close(); } catch(sql::SQLException &e) { cout << "# ERROR: SQLException in " << __FILE__; cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl; cout << "# ERROR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } break; } default: { cout << "Sorry, wrong input." << endl; } } return true; }
/** * @brief delete operation. * @param con Database connection handle. * @return true on success and false otherwise. */ bool retrieveRecord(sql::Connection *con) { string prompt = "Please select the table you want to retrieve:"; sql::Statement *stmt = con->createStatement(); sql::ResultSet *res = NULL; char tbl = selectTable(prompt); switch(tbl) { case 'c': { cout << "Currently registered Customers. " << endl; cout << "-------------------------------------------" << endl; cout << "id | fname | lname | address | age | phone " << endl; cout << "-------------------------------------------" << endl; try { res = stmt->executeQuery("SELECT * FROM Customer;"); while(res->next()) { cout << res->getString(1) << " | " << res->getString(2) << " | " << res->getString(3) << " | " << res->getString(4) << " | " << res->getInt(5) << " | " << res->getString(6) << endl; } res->close(); stmt->close(); } catch(sql::SQLException &e) { cout << "# ERROR: SQLException in " << __FILE__; cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl; cout << "# ERROR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } break; } case 'f': { cout << "Currently registered Food. " << endl; res = stmt->executeQuery("SELECT * FROM Food;"); cout << "----------------------------------------" << endl; cout << "| name | category | calorie " << endl; cout << "----------------------------------------" << endl; while(res->next()) { cout << res->getString(1) << " | " << res->getString(2) << " | " << res->getInt(3) << " | " << endl; } break; } case 'o': { cout << "Currently placed Orders. " << endl; res = stmt->executeQuery("SELECT * FROM FOrder;"); cout << "---------------------------------------------------" << endl; cout << "id | customer | food | time | quantity "<< endl; cout << "---------------------------------------------------" << endl; while(res->next()) { cout << res->getInt(1) << " | " << res->getString(2) << " | " << res->getString(3) << " | " << res->getString(4) << " | " << res->getInt(5) << " | " << endl; } break; } default: { cout << "Sorry, wrong input." << endl; } } return true; }