5.0 Programmming and database

Embed Size (px)

Citation preview

  • 8/8/2019 5.0 Programmming and database

    1/84

  • 8/8/2019 5.0 Programmming and database

    2/84

  • 8/8/2019 5.0 Programmming and database

    3/84

    Page 3 of 84

    Following is a section of a high-level languages program that adds overtime pay to basepay and stores the result in gross pay.

    grossPay = basePay + overTimePay

    y Example of high-level languages:

    i. Cii. C++ (derived from C)iii. BASICiv. Visual Basic (derived from BASIC)v. FORTRANvi. COBOLvii. Pascalviii. Java

    C++ SYNTAX

    C++ program file names often end with the .cpp, .cxx, .cc or .C (C is uppercase).

    Following is a table that consists of C++ syntax (Please refer Appendix for relatedprogram: Example 1.cpp).

    Line C++ Syntax Description

    1 4 /* .. */

    Comment: Comment helppeople read and understandyour program. You can alsoreplace this syntax with//.

    6 7

    #include#include

    Preprocessor directives: Linesthat begin with # are processedby the preprocessor before theprogram is compiled. Line 6

    notifies the preprocessor toinclude in the program thecontents of the input/outputstream header file.

    10 int main()

    The parenthesis after mainindicates that main is a programbuilding block called a function.The keyword int to the left ofmain indicates that mainreturns an integer value.

    11 & 29 { & }

    The left brace, {, must begin the

    body of every function. Acorresponding right brace, },must end each functions body.

    12 - 13charname[20];int matrixno;

    Declarations of variables: Thewords name[20] and matrixnoare the names of variables. Avariable is a location in thecomputers memory where a

  • 8/8/2019 5.0 Programmming and database

    4/84

    Page 4 of 84

    value can be stored for use by aprogram. This declarationspecifies that the variablename[20] is data of type char,which means that this variablewill hold string value (within 20

    characters including letter,number, and symbol), i.e., wholestring such as khairi, NEPAL,

    Ais_14. Variable matrixno isdata of type int, which meansthat this variable will hold integervalues, i.e., whole numbers suchas 7, -11, 0, 31914.

    15 coutvariable;

    Uses the input stream objectcinand the stream extractionoperator >>, to obtain a valuefrom the keyboard.

    15 & 26\nendl

    The backslash (\) is called anescape character. It indicatesthat a special character is to beoutput. When a backslash isencountered in a string ofcharacters, the next character is

    combined with the backslash toform an escape sequence. Theescape sequence \n meansnewline. Other examples ofescape sequence are \t, \a, and

    \r.

    The endl has same function as\n in the program.

    28 return 0;

    C++ keyword return is one ofseveral means we will use to exita function. The value 0 indicates

    that the program has terminatedsuccessfully.

    ARITHMETIC OPERATORS

    Basically C++ used mathematical operators for calculation tasks. Following is a table thatconsists of C++ syntax (Please refer Appendix for related program: Example 2.cpp).

  • 8/8/2019 5.0 Programmming and database

    5/84

    Page 5 of 84

    Line C++ Syntax Description

    26 total1 = a + c;Addition operation which sum ofa and cis stored in total1.

    28 a++; Addition operation which 1 isautomatically added to a andstored in a as a new value.

    29 a+=2; Addition operation which 2 isadded to a and stored in a as anew value.

    33 cout

  • 8/8/2019 5.0 Programmming and database

    6/84

  • 8/8/2019 5.0 Programmming and database

    7/84

    Page 7 of 84

    Please refer Appendix for related program: Example 5.cpp.

    IF/ELSE SELECTION STRUCTURE

    The if/else selection structure is a double-selection structure-it selects between twodifferent actions.

    For example, the pseudocode statement

    If students grade is greater than or equal to 60Print PassedelsePrint Failed

    print Passed if the students grade is greater than or equal to 60, but prints Failed if thestudents grade is less than 60. In either case, after printing occurs, the next pseudocodestatement in sequence is performed.

    The preceeding pseudocode if/else structure can be written in C++ as

    if ( grade >=60 )cout

  • 8/8/2019 5.0 Programmming and database

    8/84

  • 8/8/2019 5.0 Programmming and database

    9/84

    Page 9 of 84

    (Please refer Appendix for related program: Example 5.cpp).

    In the program, the users enters letter grades fro a class. Inside the while header, theparenthesized assignment (grade=cin.get()) executes first. The cin.get() function readsone character from the keyboard and stores that character in integer variable grade.Characters normally are stored in variables of type char, however, an important feature of

    C++ is that characters can be stored in any integer data type because they arerepresented as 1-byte integers in the computer.

    In the program, the value of the assignment grade = cin.get() is compared with the valueofEOF ( a symbol whose acronym stands for end-of-file). We use EOF (which normallyhas the value 1) as the sentinel value. However, you do not type the value -1, nor doyou type the letters EOF as the sentinel value. Rather, you type a system-dependentkeystroke combination that means end-of-file to indicate that you have no more data toenter.

    System such as Microsoft Windows, end-of-file can be entered by typing

    Please refer Appendix for related program: Example 10.cpp.

    DO/WHILE REPETITION STRUCTURE

    The do/while structure tests the loop-continuation condition afterthe loop body executes;therefore, the loop body executes at least once. When a do/while terminates, executioncontinues with the statement after the while clause. Note that it is not necessary to usebraces in the do/while structure if there is only one statement in the body; however, mostprogrammers include the braces to avoid confusion between the while and do/whilestructures. For example,

    while (condition)

    normally is regarded ad the header to a while structure. A do/while with no bracesaround the single statement body appears as

    dostatementwhile (condition);

    which can be confusing. The last line while (condition); - might be misinterpreted bythe reader as a while structure containing an empty statement. Thus, the do/while with

    one statement is often written as follows to avoid confusion:

    do {statement

    } while (condition);

    Please refer Appendix for related program: Example 11.cpp.

  • 8/8/2019 5.0 Programmming and database

    10/84

  • 8/8/2019 5.0 Programmming and database

    11/84

  • 8/8/2019 5.0 Programmming and database

    12/84

  • 8/8/2019 5.0 Programmming and database

    13/84

  • 8/8/2019 5.0 Programmming and database

    14/84

  • 8/8/2019 5.0 Programmming and database

    15/84

  • 8/8/2019 5.0 Programmming and database

    16/84

  • 8/8/2019 5.0 Programmming and database

    17/84

  • 8/8/2019 5.0 Programmming and database

    18/84

  • 8/8/2019 5.0 Programmming and database

    19/84

  • 8/8/2019 5.0 Programmming and database

    20/84

  • 8/8/2019 5.0 Programmming and database

    21/84

  • 8/8/2019 5.0 Programmming and database

    22/84

  • 8/8/2019 5.0 Programmming and database

    23/84

  • 8/8/2019 5.0 Programmming and database

    24/84

  • 8/8/2019 5.0 Programmming and database

    25/84

  • 8/8/2019 5.0 Programmming and database

    26/84

  • 8/8/2019 5.0 Programmming and database

    27/84

  • 8/8/2019 5.0 Programmming and database

    28/84

  • 8/8/2019 5.0 Programmming and database

    29/84

  • 8/8/2019 5.0 Programmming and database

    30/84

  • 8/8/2019 5.0 Programmming and database

    31/84

  • 8/8/2019 5.0 Programmming and database

    32/84

    Page 32 of 84

    y Select the source table or query from the current database

    y Select the fields from the table you want to include

    Figure 7.19

    Figure 7.20

  • 8/8/2019 5.0 Programmming and database

    33/84

  • 8/8/2019 5.0 Programmming and database

    34/84

  • 8/8/2019 5.0 Programmming and database

    35/84

  • 8/8/2019 5.0 Programmming and database

    36/84

  • 8/8/2019 5.0 Programmming and database

    37/84

  • 8/8/2019 5.0 Programmming and database

    38/84

  • 8/8/2019 5.0 Programmming and database

    39/84

  • 8/8/2019 5.0 Programmming and database

    40/84

    Page 40 of 84

    introduce, and once introduced we select the kind of autoform and click on OK button, andAccess does the rest.

    y Chart Wizard uses a wizard that guides us step by step in the creation of a graphic.

    y Pivot table wizard uses a wizard that guides us step by step in the creation of dynamictable.

    The Forms wizard

    To start the wizard we can do it as describe in the last point or a faster way would be fromthe Database window with the Forms object selected, by double clicking on the Createform using wizard option.

    The first window of the wizard appears:

    Figure 7.29

    Figure 7.30

  • 8/8/2019 5.0 Programmming and database

    41/84

  • 8/8/2019 5.0 Programmming and database

    42/84

    Page 42 of 84

    appear on the left side the way it will be seen in the form. Once we have selected thedistribution of our choice click Next and the following window will appear:

    In this screen we select the forms style, we can select between the various defined stylesthat Access has. By selecting a style it will appear on the left side as it will in the form.

    Once we have selected a style of our choice we click on the Next button and the lastscreen of the forms wizard will appear.

    In this window we are asked for the title of the form, this title will also be the name

    assigned to the form. Before clicking on the Finish button we can choose between:

    y Open the form to view or enter information, in this case we will see the result of theform ready for the editing of data, e.g.:

    Figure 7.32

    Figure 7.33

  • 8/8/2019 5.0 Programmming and database

    43/84

  • 8/8/2019 5.0 Programmming and database

    44/84

  • 8/8/2019 5.0 Programmming and database

    45/84

  • 8/8/2019 5.0 Programmming and database

    46/84

    Page 46 of 84

    y The Save button allows us to save the changes we are making without exiting theform.

    y The File Search button allows us to search for archives.

    y After this we have the Print and Print preview (to see the effect before sending

    the form to the printer).y Later we have the Cut , Copy , Paste , and Copy Format buttons to apply

    these same actions to the controls of our form. In order for the Cut, Copy, and Copyformat options to be available we first need to select the control/s which we want theaction to apply to. E.g., select the control to copy, click on the Copy button, positionyourself over the area where we want to copy to and click on the paste button.

    y The Undo and Redo buttons are to undo the previous actions performed ifwe have made a mistake or to redo them after undoing them.

    y To insert a hyperlink we have the button.

    y The next button makes the Field list box appear or disappear, here; all the datasource fields appear and are easier to add into the design area as we will see ahead.

    y The button makes the Toolbox appear or disappear, here all the control typesappear and are easier to add into the design area as we will see ahead.

    y With the Autoformat button we can change our form's aspect with one click to adifferent predefined format; these are the same styles that appear with the wizard.

    y All forms have an associated code page in which we can program certain actionsusing the VBA language (Visual Basic for Applications), this code page can be

    accessed by clicking on the button.

    y With the button we can make the Properties dialog appear or disappear of theselected control.

    y

    The button starts up the expression, or macros or code builder.y If we want to go to the Database window we have the button.

    y To create a new table, query, form, macro, etc... without exiting our form we can use

    the button, on dropping down we need to indicate what type of object we want tocreate in the database.

    y Finally we can access the Access help by clicking on the button.

    Figure 7.38

  • 8/8/2019 5.0 Programmming and database

    47/84

    Page 47 of 84

    The Toolbox

    To define how the information within a form will appear, and in what format it will be, weuse controls. A control is nothing more than an object that shows data, performs actions,and/or is used as decoration. E.g., we can use a text box to show data, a command buttonto open a form or report, or a line or a rectangle to separate or group controls in order tomake them more legible. In the Toolbox we have a button for each type of control that canbe added to a form.

    If the Toolbox does not appear, click on the button on the toolbar.

    If we want to create various controls of the same type we can block the control by doubleclicking on it (it will appear enclosed in a darker line), as from this moment we can createall the controls we want of this type without having to double click every time. To unblock,

    all we need to do is click on the button.

    There is a wizard that will help us to define the control, to activate it wizard click onbutton.

    The Toolbox includes the following types of controls:

    y A Label serves to visualize a fixed text, text that we write directly into its control orCaption property.

    y A Text box is usually used to present data stored in a source field of the form. Thistype of text box is called a dependant text box because it is dependant of the data inone specific field, and if we edit data in the Form view we will be changing the data atthe source. Text boxes can also be independent, e.g. to represent the results of acalculation, or to accept the entry of a users data. The data in an independent text boxis not stored anywhere. In the Control source property we have the name of theassociated table's field (when it is dependant) or a calculation formula if we want it topresent the result to us in this case the formula needs to be preceded by a = sign.

    y An Option Group is used to present a limited group of alternatives. A group ofoptions makes it easier to select a value as the user only needs then to click on thevalue he requires. There should only be a few options, otherwise it would be better touse a list box or a combo box instead of an option group.

    y When we insert a group of options the wizard will appear to help us to define thegroup.

    y The Toggle button is usually used to add a new option to an existing Option Group;

    Figure 7.39

  • 8/8/2019 5.0 Programmming and database

    48/84

  • 8/8/2019 5.0 Programmming and database

    49/84

  • 8/8/2019 5.0 Programmming and database

    50/84

    Page 50 of 84

    To move various controls at the same time, we select and move one of them and they willall move the same way.

    y Changing the size of the controls

    To change the size of a control select it so that the size controllers appear, next move the

    mouse over one of the size controllers, and when the cursor takes the form of a doublearrow, left click, maintain, and drag until the control has the desired size.

    To change the size of various controls at the same time, we select and change the size ofone of them and they will all change the same way.

    y To align various controls, we can move them one by one, guiding them through thebox, but we have an easier method in the Format menu. We select the controls toalign, drop down the Format menu, then the Align menu and select the optionaccording to how we choose to align the controls, to the left, right, up, down, and togrid. To see the effect of every option we have a diagram to the left of the option.

    y Adjusting the size of the controls

    If we want various controls to be the same size to leave our form more attractive we havea very useful tool, the Size option in the Format menu.

    We proceed in the same way as with aligning controls, selecting the controls we want toadjust, drop down the Format menu, then the Size menu, and select the most adequateoption.

    Figure 7.40

  • 8/8/2019 5.0 Programmming and database

    51/84

  • 8/8/2019 5.0 Programmming and database

    52/84

    Page 52 of 84

    We can do the same with the vertical spacing, selecting the controls that we want toadjust, drop down the Format menu, then in the Vertical Spacing menu we select the most

    adequate option for us, leaving it with the same space between controls (Make equal) asshown in the image to the left, increasing the space between the selected controls(Increase), or reduce the space (Decrease).

    CREATING REPORT

    Reports are generally used to present the data of a table or query in order to print them.

    The basic difference with reports is that the data can only be visualized or printed (it cannot be edited) and the information can be grouped and totals extracted by group moreeasily.

    In this unit we will learn how to create a report using the wizard, and how to change itsdesign once created.

    Introduction

    Figure 7.42

    Figure 7.43

  • 8/8/2019 5.0 Programmming and database

    53/84

  • 8/8/2019 5.0 Programmming and database

    54/84

    Page 54 of 84

    type of autoreport and click on the OK button, Access will do the rest.

    y The Chart wizard uses an assistant that guides us step by step through the creationof a graphic.

    y The Label wizard uses an assistant that guides us step by step through the creation

    of labels.

    The Report Wizard

    To start the wizard we can use the method explained in the previous point or a faster andeasier method would be from the Database window with the Reports object selected todouble click on the Create report by using wizard option.

    The wizard's first window will appear:

    Figure 7.45

  • 8/8/2019 5.0 Programmming and database

    55/84

  • 8/8/2019 5.0 Programmming and database

    56/84

  • 8/8/2019 5.0 Programmming and database

    57/84

    Page 57 of 84

    In this screen we can choose to sort the fields into up to four sort fields. We select the field

    by which we choose to sort the records that will appear in the report and whether we wantit in ascending or descending order, in order to select descending we click on the

    Ascending button and it will change to Descending.

    We can select a different order in each of the sort fields.This screen also allows us to add totals in an almost automatic way, if we want to add

    lines of totals we need to click on the button and the Summary optionsdialogue box will appear:

    A list of the numeric fields that we have in the repot will appear in the dialogue box, andalso the summary functions that can be selected to calculate some total. In order for thesum of a field to appear we only need to select the box in the Sum column found in thefield row. We can select various totals in this way.

    If we activate Detail and summary in the Show section, the lines of details (the sourcerecords) will appear as well as the lines of totals. If we select the Summary only option thedetail lines will not appear.

    Figure 7.49

    Figure 7.50

  • 8/8/2019 5.0 Programmming and database

    58/84

    Page 58 of 84

    If we select the Calculate percent of total for sums box it will add a percentage total thatrepresents the calculated sum over the total of all the records. E.g. if we acquire the sumof hours for a group, this percentage will be the percentage that represents the hours ofthe group within the total hours of all the groups.

    Once we have filled in the corresponding options we click on the OK button to go to thewizards next screen.

    To continue with the wizard we click on the Next> button and the following window willappear.

    In this screen we select the type of data layout within the report. By selecting a distributionthe aspect that the report will take with this distribution will appear in the diagram to theleft.

    In the Orientation section we can select from either a Portrait or a landscape printing(oblong).

    With the Adjust the field width so all fields fit on a page the wizard will generate the fields

    Figure 7.51

  • 8/8/2019 5.0 Programmming and database

    59/84

  • 8/8/2019 5.0 Programmming and database

    60/84

  • 8/8/2019 5.0 Programmming and database

    61/84

    Page 61 of 84

    records or just one per page - depending on the report. Even if various records are seenon a page, we need to indicate the design corresponding to only one record in the Detailsection.

    The Page footer section, here we put what we would like to appear at the end of eachpage.

    The Report footer, here we put what we would like to appear at the end of the report.

    We can delete the headers and footers from the View menu, Page Header/Footer andReport Header/Footer.

  • 8/8/2019 5.0 Programmming and database

    62/84

  • 8/8/2019 5.0 Programmming and database

    63/84

    Page 63 of 84

    preview to see the report before sending it to the printer.

    y We then have the Cut , Copy , Paste , and Copy format buttons to applythese same actions to the controls in our report. In order for the Cut, Copy, and Copyformat to be activated we need to first select the control/s onto which we wish to applythe action. E.g. select the control to copy, click on the copy button, then position the

    cursor in the area where we want to leave the copy and click on the Paste button.

    y The Undo and Redo buttons are for undoing the last action if we made amistake, or redoing an action that we have undone.

    y To insert a hyperlink we have the button.

    y The next button makes the list of fields box appear and disappear, in which all thesource data fields appear in order to make them easier to add to the design area aswe will see ahead.

    y The button makes the Toolbox appear or disappear in which all the types ofcontrols appear in order to make them easier to add to the design area as we will seeahead.

    y The button allows us to modify the group levels as we will see ahead.

    y With the Autoformat button we can change the aspect of our report to a predefineddesign from Access with just one click; these are the same styles that appear in thereport wizard.

    y All reports have an associated code page in which we can program various actionsusing VBA language (Visual Basic for Applications), this code page can be accesses

    by clicking on the button.

    y With the button we can make the Properties box of the selected control appear ordisappear. The report's properties are much the same as those of a form.

    y The button starts the expressions, or macros or code generator.

    y If we want to go to the Database window we have the button.

    y To create a new table, query, report, macro, etc... without exiting our report we can

    use the button, on dropping it down we can select the type of object we want tocreate in the database.

    y And finally we can access the Access help by clicking on the button.

    The Toolbox

    To define what information should appear in the report, and in what format it should be,the same controls can be used as in a form although some controls for example the

    Figure 7.57

  • 8/8/2019 5.0 Programmming and database

    64/84

  • 8/8/2019 5.0 Programmming and database

    65/84

    Page 65 of 84

    y And finally we can add more complex controls with the button.

    We see that the management of controls in reports is identical to the controls of a form., ifyou have any doubt about how to add a control, how to move it, copy it, change its size,how to adjust its size, or aligning the various controls revise the previous unit.

    Printing a Report

    Printing a report can be done in various ways.

    y Printing directly

    If we are in the Database window:

    Select the Report tab. Click on the name of the report that we want to print to select it. We

    click on the button on the toolbar, the report is sent directly to the printer. In this caseall of the pages in the document will be printed with the options defined at that moment.

    Before sending the printing to the document it is convenient to check the defined optionsat that moment, and for this we need to open the Print dialogue box.

    y Opening the Print dialogue box

    If we are in the Database window:

    Select the Report tab. Click on the name of the report that we want to print to select it. Ifwe drop down the File menu and select the Print... option the Print dialogue box will openin which you can change some of the parameters in the printing as we will explain to younext:

    If we have various printers connected to the computer (as we often do when they arenetwork printers), dropping down the Name: combo box we can select the printer to whichwe want to send the printing.

    Figure 7.59

  • 8/8/2019 5.0 Programmming and database

    66/84

    Page 66 of 84

    In the Print Range section we can specify whether we want to print the whole report (All)or just a few pages.If we only want to print a few pages we can specify the initial page of the interval to print inthe from: box, and in the To: box specify the final page.If we have records selected when we open the dialogue box we can select the Selected

    Record(s) option to print only these records.

    In the Copies section we can specify the Number of Copies: to print. If the Collate optionis not selected then it will print a full copy and after that another copy, while if we activatethe Collate option it will print the copies of each page together.

    The Print to File option allows us to send the result of the printing to a file in the hard driveinstead of sending it to the printer.With the Properties button we can access the printer properties window, this window willchange depending on the model printer we have, but will allow us to define the type ofprinting e.g. in color or black and white, in high quality or draft copy, the type of paper weuse, etc...

    With the Setup ... button we can configure the page, change the margins, print variouscolumns, etc...

    And lastly we click on the OK button and the printer will start. If we close the windowwithout accepting, nothing will be printed.

    y Opening a report in Previous view.

    To check whether the printing will come out well it is convenient to open the reportpreviously on the screen to check if it is ok to go ahead and send it to the printer. To opena report in preview from the Database window we need to follow these steps:

    With the Reports object selected, click on the name of the report to select it.

    Next we click on the button and the report preview will open.

    The Preview Window

  • 8/8/2019 5.0 Programmming and database

    67/84

    Page 67 of 84

    In this window we see the report in the way that it will be printed.

    To pass over the various pages we have a scroll bar in the lower part of the screen withthe buttons that we know already to go to the first page, to the next page, to a specificpage, to the previous page or to the last page.

    At the top we have a toolbar with buttons that are already familiar to us:

    y to go to design view

    y to send the report to the printer

    y to go to the Database window

    y to create a new object

    y to access help.

    y the magnifying glass allows us to draw near or draw away from the report.

    y allows us to visualize a whole page on the screen.

    y reduces the size of the report in order to see two pages of the report on the samescreen.

    y allows us to see up to six pages on the screen at the same time.

    y adjusts the size so that a whole page can be seen on the screen, and ifwe drop down the menu we can select a zoom porcentage to see the page closer orfurther, it has the same function as the magnifying glass but allows more sizes.

    y opens the Page setup window where we can change the margins, theorientation of the paper, etc...

    y sends the report to a Word document, dropping down the box we can select tosend it to various Microsoft applications, Excel for example.

    y will close the preview without sending the report to the printer.

    Sorting and Grouping

    As we have already seen, with the wizard's help we can define grouping levels for therecords in the report and extract a special heading or line of totals for each group; we canalso define a determined order for the records that appear in the report.To define the order of the records, create a new grouping level or modify the levels thatwe have already defined in an already defined report, we open it in design view and click

    on the button on the toolbar.

    Figure 7.60

  • 8/8/2019 5.0 Programmming and database

    68/84

  • 8/8/2019 5.0 Programmming and database

    69/84

    Page 69 of 84

    In the bottom part we have each grouping and sorting columns properties.The Group header property is where we indicate whether we want to include a groupheader; it will contain all the data we want to print only when a group starts. If you changethe property to Yes you will see that a new section appears in Report design window forthe group header.

    In the Group footer property we indicate whether we want to include group footer, and itwill contain all the data that we want to print only when the group ends and is normallyused to print the group totals. If you change the property to Yes you will see that a newsection appears in the report design window for the group footer.

    In the Group on property we can choose between .

    If we select Each value, it will sort the records in the report by field, and every time thefield value changes it will end the group and start a new group of values. If we selectPrefix Characters, in the Group interval property we put a number of characters, and it will

    group by n first characters in the field.

    The Group interval property serves to indicate a number of characters if we have theGroup in property with a Prefix Characters value.

    It also serves to form groups of a fixed number of records e.g. if we want to form groups offive records, we put Each value in the Group on property and we put 5 in the Groupinterval property.

    And lastly we have the Keep together property where we can choose between

    If we select Whole group it will try to write the group header, the detail section, and the

    group footer on the same page, i.e. if after the records of the first group have been printed

    and there is half a page left empty but the second group does not fit in this space, it will

    skip the page and start the new group on a new page.

    If we select With First Detail it will only print the group header if it can also print the firstdetail record.

    If we select No, it will be printed without maintaining the group header, the detail section,and the group footer on the same page.

    THE RELATIONAL DATABASE MODEL

  • 8/8/2019 5.0 Programmming and database

    70/84

  • 8/8/2019 5.0 Programmming and database

    71/84

  • 8/8/2019 5.0 Programmming and database

    72/84

  • 8/8/2019 5.0 Programmming and database

    73/84

  • 8/8/2019 5.0 Programmming and database

    74/84

    Page 74 of 84

    P_ONHAND SMALLINT NOT NULL,P_MIN SMALLINT NOT NULL,P_PRICE NUMBER(8,2) NOT NULL,P_DISCOUNT NUMBER(5,2) NOT NULL,V_CODE INTEGERPRIMARY KEY (P_CODE),

    FOREIGN KEY (V_CODE) REFERENCES VENDORON DELETE RESTRICTON UPDATE CASCADE);

    Please refer Appendix for some common SQL data types.

    CREATE DOMAIN

    Format:

    CFREATE DOMAIN AS DATA_TYPE[DEFAULT ][CHECK ()]

    Example:

    CREATE DOMAIN MARITAL_STATUS AS VARCHAR(8)CHECK (VALUE IN (Single,Married,Divorced,Widowed));

    You can use the domain name instead of the attributes data type in the CREATETABLE command when you define a new table. For example:

    CREATE TABLE EMPLOYEE (EMP_NUM INTEGER NOT NULL CONSTRAINT EMPPK PRIMARYEMP_LNAME VARCHAR(15) NOT NULL,EMP_FNAME VARCHAR(15 NOT NULL,EMP_STATUS MARITAL_STATUS NOT NULL,

    Another advantage of using domains is that you can draw domain values from othertables by including a SELECT statement in the CHECK clause. For example, you couldhave a table called DISCOUNTBL to store all the valid discount rates a company might

    offer. In this case, the DISCOUNTBL table might be defined to contain a singleDISCOUNT attribute. In turn, this table might then contain three rows containing thevalues 10.00, 15.00, and 20.00. Given the existence of such a table, the CREATEDOMAIN statement would be written as follows:

    CREATE DOMAIN DISCOUNT_RATE AS NUMBER (5,2)CHECK (VALUE IN (SELECT DISCOUNT FROM DISCOUNTBL));

    To delete a domain definition, use the DROP DOMAIN statement. The syntax is:

  • 8/8/2019 5.0 Programmming and database

    75/84

    Page 75 of 84

    DROP DOMAIN [RESTRICT | CASCADE]

    Example:

    DROP DOMAIN MARITAL_STATUS CASCADE;

    DATA ENTRY

    Format:

    INSERT INTO VALUES (attribute1 value, attribute2 value, etc.)

    Example:

    INSERT INTO VENDORVALUES (21225, Bryson, Inc., Smithson, 615, 223-3234, TN, Y);

    INSERT INTO PRODUCTVALUES (BRT-345, Titanium drill bit, 10/18/02, 75, 10, 4.50, 0.06, NULL);

    SAVING THE TABLE CONTENTS

    Format:

    COMMIT

    Example:

    COMMIT PRODUCT

    LISTING THE TABLE CONTENTS

    Format:

    SELECT *FROM

    Example:

    SELECT *FROM PRODUCT;

    Or

    SELECT P_CODE, P_DESCRIPT, P_INDATE, P_ONHAND, P_MIN, P_PRICE,P_DISCOUNT, V_CODEFROM PRODUCT;

  • 8/8/2019 5.0 Programmming and database

    76/84

  • 8/8/2019 5.0 Programmming and database

    77/84

    Page 77 of 84

    The Integrated Development EnvironmentMuch of the popularity of Visual Basic comes from its Integrated DevelopmentEnvironment or IDE for short.

    Running the IDEYou can choose from several ways to launch the Visual Basic IDE, as is true for anyWindows executable:

    y You can run the Visual Basic 6 environment from the Start Menu; the exact path to themenu command depends on whether you have installed Visual basic as part of theMicrosoft Visual Studio suite.

    y You can create a shortcut to the IDE on your desktop and run it by simply double-clicking on it.

    y When Visual Basic is installed, it registers the .vbp, .frm, .bas, and a few otherextensions with the operating system. Therefore, you can run the environment bydouble-clicking on any Visual Basic file.

    y

    If you have installed Microsoft Active Desktop, you can create a shortcut to the VisualBasic IDE on the system taskbar. This is probably the fastest way to run the IDE: itssimilar to a desktop shortcut, but you dont have to minimize other windows to uncoverit.

    Selecting the Project Type

    The first time you run the Visual basic IDE, youre asked to select the type of project youwant to create, as you can see in Figure 1.1. Choose Standard EXE and click Openbutton to start working with a regular project that, once compiled, will deliver a stand-aloneEXE application. You can also decide to tick the Dont show this dialog in future checkbox if you want to avoid this operation the next time you launch the IDE.

  • 8/8/2019 5.0 Programmming and database

    78/84

    Page 78 of 84

    IDE Windows

    Figure 7.65

    Figure 7.66

  • 8/8/2019 5.0 Programmming and database

    79/84

  • 8/8/2019 5.0 Programmming and database

    80/84

    Page 80 of 84

    y One property that very control has and thats very important to Visual Basicprogrammers is the Name property. This is the string of characters that identifies thecontrol in code.

    y Microsoft suggests that you always use the same three-letter prefix for all the controlsof a given class. The control classes and their recommended prefixes are shown inTable 1-1.

    Control Class Prefix Control Class Prefix

    CommandButton cmd Data dat

    TextBox txt HScrollBar hsb

    Label lbl VScrollBar vsbPictureBox pic DriveListBox drv

    OptionButton opt DirListBox dir

    CheckBox chk FileListBox fil

    ComboBox cbo Line lin

    ListBox lst Shape shpTimer tmr OLE ole

    Frame fra Form frm

    y Rename the Text1 through Text4 controls as txtWidth, txtHeight, txtPerimeter, andtxtArea respectively.

    y Rename the Command1 control as cmdEvaluate.

    y Rename the Label1 through Label4 controls as lblWidth, lblHeight, lblPerimeter, andlblArea respectively.

    Moving and Resizing ControlsIDE offers you many ways to modify the position and size of your controls without mucheffort.

    y Select one or more controls, and move them as a single entity using the mouse.y Move one or more controls with arrow keys while you press the Ctrl key. The steps

    along the x- and y-axes are determined by the Grid Units settings.

    y Resize the selected control(s) by using the arrow keys while you press the Shift key.You can also resize a control by dragging one of the blue handles surrounding it whenit is selected. Like the move operation, the resize step depends on the Grid Unitssettings.

    y Center a control or a group of controls on the form, either horizontally or vertically,using the Center In Form submenu of the Format menu.

    y Align a group of controls with respect to another control using the commands in theAlign submenu of the Format menu. The control used as a reference in the aligningprocess is the one that was selected last (that is, the one with blue handles around it).

    y Resize a group of controls by selecting them and invoking a command in the makeSame Size submenu of the Format menu. All selected controls will be resized toreflect the size of the control that was selected last.

    y You can align or resize a group of controls by selecting them, pressing F4 to displaythe Properties window, and then manually modifying the Left, Top, Width, or Heightproperties. This procedure is useful when you know the absolute position or size of thecontrols.

  • 8/8/2019 5.0 Programmming and database

    81/84

    Page 81 of 84

    Setting the Tab OrderYou can set the correct Tab order sequence by assigning a proper value to the TabIndexproperty for all the controls that can receive the input focus, starting with 0 for the controlthat should receive the input focus when the form appears and assigning increasingvalues for all the others. Heres a trick well known among Visual Basic programmers thatsolves the problem with relatively little effort:

    y Select the last control in your planned Tab order.

    y Press the Ctrl+Shift+T key combination to activate the Properties window. For mostcontrols, this combination selects the TabIndex properties; for others, you might needto press it more than once.

    y Press the 0 key, thus assigning a 0 to the TabIndex property of the selected control.

    y Click on the next to last control in the Tab order, and press the 0 key again; thisassigns a 0 to the TabIndex property of the current control and 1 to the TabIndexproperty of the last control. This occurs because Visual Basic prevents you from usingthe same TabIndex value for two or more controls on the same form.

    y Repeat step 4, working backward in the Tab order sequence and pressing the 0 keyafter selecting each control. When you reach the first control in the sequence, theTabIndex property for all the controls on the form will be set correctly.

    Adding Code

    To write code within the Click event, you just select the cmdEvaluate control and thenpress the F7 key, or right-click on it and then invoke the View Code command from thepop-up menu. Or you simply double-click on the control using the left mouse button. In allcases, the code editor window appears, with the flashing cursor located between thefollowing two lines of code:

    Private Sub cmdEvaluate_Click ( )

    End Sub

    Visual Basic has prepared the template of the Click event procedure for you, and youhave to add one or more lines of code between the Sub and End Sub statements. In thissimple program, you need to extract the values stored in the txtWidth and txtHeightcontrols, use them to compute the rectangles perimeter and area, and assign the resultsto the txtPerimeter and txtArea controls respectively:

    Private Sub cmdEvaluate_Click ( )

    Declare two floating point variables.Dim reWidth As Double, reHeight As Double

    Extract values from input TextBox controls.reWidth = CDbl(txtWidth.Text)reHeight = CDbl(txtHeight.Text)

    Evaluate results and assign to output text boxes.txtPerimeter.Text = CStr((reWidth + reHeight) * 2)txtArea.Text = CStr(reWidth * reHeight)

  • 8/8/2019 5.0 Programmming and database

    82/84

    Page 82 of 84

    End Sub

    Running and Debugging the Program

    Youre finally ready to run this sample program. You can start its execution in several

    ways: by invoking the Start command from the Run menu, by clicking the correspondingicon on the toolbar, or by pressing the F5 key.

    In all cases, youll see the form designer disappear and be replaced (but not necessarily inthe same position on the screen) by the real form.

    You can enter any value in the leftmost TextBox controls and then click on the Evaluatebutton (or press the Alt+E key combination) to see the calculated perimeter and area inthe rightmost controls.

    When youre finished, end the program by closing its main (and only) form.

    Refining the Sample Program

    Our first Visual Basic project, Rectangle.vbp, is just a sample program, but this is noexcuse not to refine it and turn it into a complete and robust, albeit trivial, application.

    The first type of refinement is very simple. Because the txtPerimeter and txtArea controlsare used to show the results of the computation, it doesnt make sense to make theircontents editable by the user. You can make them read-only fields by setting their Lockedproperty to True. Some programmers prefer to use Label controls to display result valueson a form, but using read-only TextBox controls has an advantage: The end user cancopy their contents to the clipboard and paste those contents into another application.

    A second refinement is geared toward increasing the applications consistency andusability. Lets suppose that your user uses the Rectangle program to determine theperimeter and area of a rectangle, takes note of the results, and then enters a new widthor a new height (or both). Unfortunately, an instant before your user clicks on the Evaluatebutton the phone rings, engaging the user in a long conversation. When he or she hangsup, the form shows a plausible, though incorrect, result. How can you be sure that thosevalues wont be mistaken for good ones? The solution is simple, indeed: as soon as theuser modifies either the txtWidth or the txtHeight TextBox controls, the results fields mustbe cleared. In visual basic, you can accomplish this task by trapping each source controlsChange event and writing a couple of statements in the corresponding event procedure.Since Change is the default event for TextBox controls just as the Click event is forCommandButtons controls you only have to double-click the txtWidth and txtHeight

    controls on the form designer to have Visual Basic create the template for thecorresponding event procedures.

    This is the code that you have to add to the procedures:

    Private Sub txtWidth_Change( )

    txtPerimeter.Text = txtArea.Text =

  • 8/8/2019 5.0 Programmming and database

    83/84

    Page 83 of 84

    End Sub

    Private Sub txtHeight_Change( )

    txtPerimeter.Text =

    txtArea.text =

    End Sub

    The purpose of the next refinement that I am proposing is to increase the programsrobutness. To see what I mean, run the Rectangle project an press the Evaluate buttonwithout entering width or height values: the program raises a Type Mismatch error whentrying to extract a numeric value from the txtWoidth control. If this were a real-world,compiled application, such an untrapped error would cause the application to endabruptly, which is, of course, unacceptable. All errors should be trapped and dealt with ina convenient way. For example, you should show the user where the problem is and howto fix it. The easiest way to achieve this is by setting up an error handler in the

    cmdEvaluate_Click procedure, as follows.

    Private Sub cmdEvaluate_Click( )

    Declare two floating point variables.Dim reWidth As Double, reHeight As DoubleOn Error GoTo WrongValues

    Extract values from input textbox controls.reWidth = CDbl (txtWidth.Text)reHeight = CDbl (txtHeight.Text)Ensure that they are positive values.

    If reWidth

  • 8/8/2019 5.0 Programmming and database

    84/84

    Question

    1. What is if/else statement used for

    ___________________________________________________________________________________________________________________________________________________

    2. Give the three type of computer language

    ___________________________________________________________________________________________________________________________________________________

    3. What is Arithmetic Operator

    ___________________________________________________________________________________________________________________________________________________

    REFERENCE1 Programming Microsoft Visual Basic Francesco Balena Microsoft Press