Professional Documents
Culture Documents
DBMS Lab Manual CaseStudy
DBMS Lab Manual CaseStudy
11
Application Development-Tutorials
11.1 11.2 11.3 11.4 11.5 11.6 Tutorials using Oracle 9i & VB6.0..... Tutorials using MS-Access & VB6.0..... Tutorials using MS-Sql & VB6.0..... Compamy Database.... Report Generation.... Additional Examples.. 426 448 449 453 495 499
426
Chapter 11
In Chapters 1 through Chapter 10, we have discussed database concepts and i am sure that it would be incomplete if database application development is not covered. This chapter is dedicated to fulfill this requirement. The aim is to describe the steps involved in developing a database application for a small company using Oracle9i as back-end and VB 6.0 as front-end. However, instead of starting with a large application like the company database, we shall first present few simple tutorials. You would definitely get complete details of various issues related to the design of a customized application development. The only requirement to understand this chapter is know the basics of VB 6.0. This chapter starts with few small tutorial examples and then it takes you to Software Requirement Specification (SRS) of Company database and explains the procedures to create forms, command buttons, VB code, and many more. By practicing this case study, you can develop any other application package with out any additional efforts. The entire chapter is divided into four parts each one considers a different backend tool.
PART - I
11.1 TUTORIALS USING ORACLE9i & VB6.0
We shall begin with tutorials that use Oracle9i DBMS as back-end and VB6.0 as front-end tool. It is assumed that the reader is aware of VB6.0 already so that understanding the tutorials become easier.
427
11.1.1 Tutorial - I
The aim of this tutorial is to: Create a simple table 'Test' in Oracle9i with two attributes 'RegNo' and 'Name' and develop an application in VB6.0 to add new records, browse, modify, and delete the records. We shall assume the following hardware and software: Operating System: Database: Front-End Tool:
Step-1:
Go to the SQL window. Click on Start > All programs > Oracle-OraHome90 > Application Development > SQL Plus. Type the following code in the SQL prompt: CREATE TABLE Test ( RegNo VARCHAR2(10), Name VARCHAR2 (20) NOT NULL, PRIMARY KEY(RegNo));
Step-2:
Step-3: Step-4:
Click Start > Control Panel > Administrative tools > Data Sources(ODBC). Press Add button and enter a name for the DSN (Data Source Name). Leave the rest blank. In this example, it is named as Elective. The screenshots of Step-3 and Step-4 are shown below:
428
Chapter 11
Step-5:
Click Start > All Programs > Microsoft Visual Studio 6.0 > Microsoft Visual Basic 6.0. In the New Project Window, select Standard EXE icon and then click the Open button. You will see a new Project window and a form window with the default names Project1 and Form1. Change Name property of the form to Demo1 and the caption property to Demo1. Draw the following controls and assign the names as given below: Name Label1 Label2 txtRegNo txtName cmdFirst Name Type label label2 Text box Text box Command Button << Type Caption RegNo Name
Step-6: Step-7:
Caption
429
Command Button < Command Button > Command Button >> Command Button &Save Command Button &Cancel Command Button &Delete Command Button Exit
After creating these controls, the form should look like as shown in Figure 11.1. Step-8: Before typing the program, do the following: Click Project > References and check Microsoft Active X Data Objects 2.5 Library. See Fig. 11.2.
430
Chapter 11
431
rstStudent.MoveLast End If End If End If End Sub First Button (<<) Private Sub cmdFirst_Click() On Error Resume Next rstStudent.MoveFirst cmdPrev.Enabled = False cmdNext.Enabled = True End Sub Last Button (>>) Private Sub cmdLast_Click() On Error Resume Next rstStudent.MoveLast cmdNext.Enabled = False cmdPrev.Enabled = True End Sub Next Button (>) Private Sub cmdNext_Click() On Error Resume Next rstStudent.MoveNext If rstStudent.EOF Then rstStudent.MoveLast End If cmdPrev.Enabled = True End Sub Previous Button (<) Private Sub cmdPrev_Click() On Error Resume Next rstStudent.MovePrevious If rstStudent.BOF Then rstStudent.MoveFirst End If cmdNext.Enabled = True Exit Sub End Sub New Button Private Sub cmdNew_Click() rstStudent.AddNew 'Create a new record and clear txtRegNo.Text = "" txtName.Text = "" txtRegNo.SetFocus End Sub
432
Save Button Private Sub cmdSave_Click() On Error Resume Next rstStudent!RegNo = txtRegNo.Text rstStudent!Name = txtName.Text rstStudent.Update cmdFirst.Enabled = True cmdPrev.Enabled = True cmdNext.Enabled = True cmdLast.Enabled = True rstStudent.Requery End Sub Form Load Section
Chapter 11
Private Sub Form_Load() On Error Resume Next 'Create connection object (for Oracle database) Set DB = New Connection DB.Open "DSN=Elective;UID=Scott;PASSWORD=Tiger" 'Create recordset object Set rstStudent = New Recordset rstStudent.CursorLocation = adUseClient rstStudent.Open "Select * from Test", DB, adOpenDynamic, adLockOptimistic 'Bind the form controls to database fields Set txtRegNo.DataSource = rstStudent txtRegNo.DataField = "RegNo" Set txtName.DataSource = rstStudent txtName.DataField = "Name" 'Check for empty status of the table Dim count As Integer While Not rstStudent.EOF count = count + 1 rstStudent.MoveNext Wend If count = 0 Then 'no records cmdFirst.Enabled = False cmdPrev.Enabled = False cmdNext.Enabled = False cmdLast.Enabled = False MsgBox "No Records in the Table", vbExclamation, "Error" Else rstStudent.MoveFirst End If 'rstStudent.MoveFirst End Sub Exit Button Private Sub cmdExit_Click() End End Sub
433
Step-10: Save the project with appropriate name (in this example it is Demo1). You can set the name of the project by selecting Project > Project1 properties and type DatabaseDemo in the Project Name text box and then click OK button (See Figure 11.3). Step-11: Press F5 to run the application.
11.1.2 Tutorial - II
This tutorial is an extension of Tutorial-I and in fact the solution of the exercise given in the previous section. However, we need to create a new table called Projects as shown below:
Step-1: CREATE TABLE Projects ( PNo INTEGER, PName VARCHAR2(20), RegNo VARCHAR2(10), PRIMARY KEY(PNo), FOREIGN KEY(RegNo) REFERENCES Test(RegNo));
434
Step-2: Step-3: Create a combo box and name it as Combo1. Create a list box and name it as List1.
Chapter 11
The other controls are same as the previous Tutorial. However, some new GUI components have been added to this project. The first one is a menu and the second one is a tool bar. We shall explain the steps involved in designing these controls.
Step-4: To create a menu, click Tools > Menu Editor (ctrl + E). Add main menu items and sub menu items as shown in Figure 11.4.
435
436
Chapter 11
437
rstStudent.MoveLast End If End If End If End Sub Private Sub mnuNew_Click() rstStudent.AddNew 'Create a new record and clear txtRegNo.Text = "" txtName.Text = "" txtRegNo.SetFocus cmdSave.Enabled = True mnuSave.Enabled = True Toolbar1.Buttons.Item(2).Enabled = True End Sub Private Sub mnuSave_Click() rstStudent!RegNo = txtRegNo.Text rstStudent!Name = txtName.Text rstStudent.Update cmdFirst.Enabled = True cmdPrev.Enabled = True cmdNext.Enabled = True cmdLast.Enabled = True Combo1.AddItem (rstStudent!Name) rstStudent.Requery cmdSave.Enabled = False mnuSave.Enabled = False Toolbar1.Buttons.Item(2).Enabled = False End Sub Private Sub Toolbar1_ButtonClick(ByVal Button As MSComCtlLib.Button) On Error Resume Next Select Case Button.Key Case "New" rstStudent.AddNew 'Create a new record and clear txtRegNo.Text = "" txtName.Text = "" txtRegNo.SetFocus cmdSave.Enabled = True mnuSave.Enabled = True Toolbar1.Buttons.Item(2).Enabled = True Case "Save" On Error Resume Next rstStudent!RegNo = txtRegNo.Text rstStudent!Name = txtName.Text rstStudent.Update cmdFirst.Enabled = True cmdPrev.Enabled = True cmdNext.Enabled = True cmdLast.Enabled = True Combo1.AddItem (rstStudent!Name) rstStudent.Requery cmdSave.Enabled = False mnuSave.Enabled = False
438
Chapter 11
Toolbar1.Buttons.Item(2).Enabled = False Case "Undo" rstStudent.CancelUpdate rstStudent.Requery cmdSave.Enabled = False mnuSave.Enabled = False Toolbar1.Buttons.Item(2).Enabled = False Case "Delete" On Error Resume Next Dim intChoice If Not rstStudent.EOF Then intChoice = MsgBox("Are sure you want to delete?", vbYesNo + vbCritical) If intChoice = vbYes Then rstStudent.Delete rstStudent.MoveNext If rstStudent.EOF Then rstStudent.MoveLast End If End If End If Case "Help" 'ToDo: Add 'Help' button code. MsgBox "Under construction." End Select End Sub Private Sub cmdCancel_Click() rstStudent.CancelUpdate rstStudent.Requery cmdSave.Enabled = False mnuSave.Enabled = False Toolbar1.Buttons.Item(2).Enabled = False End Sub Private Sub cmdDelete_Click() On Error Resume Next Dim intChoice If Not rstStudent.EOF Then intChoice = MsgBox("Are sure you want to delete?", vbYesNo + vbCritical) If intChoice = vbYes Then Combo1.RemoveItem (rstStudent!Name) rstStudent.Delete rstStudent.MoveNext If rstStudent.EOF Then rstStudent.MoveLast End If End If End If End Sub Private Sub cmdExit_Click() End End Sub Private Sub cmdFirst_Click() On Error Resume Next
439
rstStudent.MoveFirst cmdPrev.Enabled = False cmdNext.Enabled = True End Sub Private Sub cmdLast_Click() On Error Resume Next rstStudent.MoveLast cmdNext.Enabled = False cmdPrev.Enabled = True End Sub Private Sub cmdNew_Click() rstStudent.AddNew 'Create a new record and clear txtRegNo.Text = "" txtName.Text = "" txtRegNo.SetFocus cmdSave.Enabled = True mnuSave.Enabled = True Toolbar1.Buttons.Item(2).Enabled = True End Sub Private Sub cmdNext_Click() On Error Resume Next rstStudent.MoveNext If rstStudent.EOF Then rstStudent.MoveLast End If cmdPrev.Enabled = True End Sub Private Sub cmdPrev_Click() On Error Resume Next rstStudent.MovePrevious If rstStudent.BOF Then rstStudent.MoveFirst End If cmdNext.Enabled = True Exit Sub End Sub Private Sub cmdSave_Click() On Error Resume Next rstStudent!RegNo = txtRegNo.Text rstStudent!Name = txtName.Text rstStudent.Update cmdFirst.Enabled = True cmdPrev.Enabled = True cmdNext.Enabled = True cmdLast.Enabled = True Combo1.AddItem (rstStudent!Name) rstStudent.Requery cmdSave.Enabled = False mnuSave.Enabled = False Toolbar1.Buttons.Item(2).Enabled = False
440
End Sub
Chapter 11
Private Sub Combo1_Click() List1.Clear 'Populate combo box and list box Set rstProject = New Recordset rstProject.Open "Select PName from Projects,Test where Projects.RegNo = Test.RegNo and Test.Name = " & "'" & Combo1.Text & "'", DB, adOpenDynamic, adLockOptimistic While Not rstProject.EOF List1.AddItem (rstProject!PName) rstProject.MoveNext Wend End Sub Private Sub Form_Load() On Error Resume Next 'Create connection object (for Oracle database) Set DB = New Connection DB.Open "DSN=Elective;UID=Scott;PASSWORD=Tiger" 'Create recordset object Set rstStudent = New Recordset rstStudent.Open "Select * from Test", DB, adOpenDynamic, adLockOptimistic 'Bind the form controls to database fields Set txtRegNo.DataSource = rstStudent txtRegNo.DataField = "RegNo" Set txtName.DataSource = rstStudent txtName.DataField = "Name" 'Check for empty status of the table Dim count As Integer While Not rstStudent.EOF count = count + 1 rstStudent.MoveNext Wend If count = 0 Then 'no records cmdFirst.Enabled = False cmdPrev.Enabled = False cmdNext.Enabled = False cmdLast.Enabled = False MsgBox "No Records in the Table", vbExclamation, "Error" Else rstStudent.MoveFirst End If Combo1.ToolTipText = "Select the Student Name." List1.ToolTipText = "List of projects being operated by the above student" 'populate the combo box with names While Not rstStudent.EOF Combo1.AddItem (rstStudent!Name) rstStudent.MoveNext Wend rstStudent.MoveFirst cmdSave.Enabled = False mnuSave.Enabled = False
441
Toolbar1.Buttons.Item(2).Enabled = False End Sub Private Sub mnuExit_Click() End End Sub Step-9: Finally, save the form and the project. In our example - Demo2 is the form name and DataBaseDemo is the name of the project.
Step-10: Run the application and test it with some sample data. Exercise Create a third table "Course" and add appropriate foreign keys. Modify the design presented in this section to incorporate this table too.
Step-3:
442
Chapter 11
Control Type Frame Label Label Label Text box Text box Text box Command button Command button Frame DataGrid Command button Command button Frame Check box Check box Label Label ADODC
Property Frame1 User Name Password Confirm Password txtUsrName txtPass txtConform cmdCancel cmdSave Frame2 DataGrid1 cmdShow cmdConnect Frame3 CheckM CheckD Label3 Label4 Adodc1
Name New User &Cancel &Save Existing Users Password Table S&how users Connec&t Privileges Allow Modify Allow Delete Adodc1
Caption
Connection String: Provider=MSDAORA.1;User ID=scott;Persist Security Info=False Password: Tiger Record Source: SELECT ID, passwd FROM USERS ORDER BY ID UserName: Scott
Step-4:
Let us see what the main menus are and sub menu items that are required for this application. Edit Help Change Password Modify User Delete User Ctrl+D Contents About
Step-5:
The next task which needs to be done is the creation of tool bar as shown in Figure 11.8 (this figure shows the complete form also). Type the following code for various controls of this form. Option Explicit Dim DB As Connection Dim rstUser As Recordset Private Sub cmdCancel_Click() rstUser.CancelUpdate Disable_fields End Sub
Step-6:
443
Private Sub cmdConnect_Click() MsgBox "Plug-in your application (main form) here ......", vbInformation End Sub Private Sub cmdSave_Click() On Error GoTo err1 Dim strEString As String Set rstUser = New Recordset rstUser.Open "Select * from users order by id", DB, adOpenDynamic, adLockOptimistic rstUser.AddNew rstUser!id = txtUsrName.Text strEString = Encrypt_password rstUser!passwd = strEString If txtPass = txtconfirm Then rstUser.Update Disable_fields Else MsgBox "Passwords do not match, please reenter", vbCritical, "Password Error" txtPass.SetFocus SendKeys "{Home}+{End}" End If Exit Sub err1: MsgBox Err.Description End Sub Private Sub cmdShow_Click() Set DataGrid1.DataSource = Adodc1 Adodc1.Refresh End Sub Private Sub Form_Load() On Error Resume Next Set DB = New Connection DB.Open "DSN=Elective;UID=scott;password=tiger;" Set rstUser = New Recordset rstUser.Open "Select * from Users order by id", DB, adOpenDynamic, adLockOptimistic ' a dummy record is created rstUser.AddNew rstUser!id = "dummy" rstUser!passwd = "dummy" rstUser.Update Set txtUsrName.DataSource = rstUser txtUsrName.DataField = "id" Set txtPass.DataSource = rstUser txtPass.DataField = "passwd" DataGrid1.AllowAddNew = False DataGrid1.AllowDelete = False DataGrid1.AllowUpdate = False Disable_fields cmdShow.SetFocus End Sub
444
Private Sub mnuchange_Click() MsgBox "Left as Exercise", vbInformation End Sub
Chapter 11
Private Sub mnuDelete_Click() Dim intChoice As Integer Dim strIN As String strIN = InputBox("Enter the User Name") If strIN = "" Then 'user has pressed Cancel button Exit Sub End If Set rstUser = New Recordset rstUser.Open "Select * from Users where id = " & "'" & strIN & "'", DB, adOpenDynamic, adLockOptimistic If rstUser.EOF Then MsgBox "Record not found, can't delete", vbExclamation, "Missing Record" Else intChoice = MsgBox("Are you sure you want to Delete?", vbCritical + vbYesNo, "Delete") If intChoice = vbYes Then rstUser.Delete End If End If End Sub Private Sub mnuNew_Click() Enable_fields txtUsrName.SetFocus End Sub Private Sub mnuSave_Click() cmdSave_Click End Sub Private Sub Toolbar1_ButtonClick(ByVal Button As MSComCtlLib.Button) On Error Resume Next Select Case Button.Key Case "Help" 'ToDo: Add 'Help' button code. 'MsgBox "Add 'Help' button code." Case "Delete" mnuDelete_Click Case "Undo" cmdCancel_Click Case "Save" cmdSave_Click Case "New" Enable_fields txtUsrName.SetFocus Case "Open" 'ToDo: Add 'Open' button code. End Select End Sub
445
Private Sub mnuExit_Click() End End Sub Private Sub Disable_fields() txtUsrName.Text = "" txtPass.Text = "" txtconfirm.Text = "" txtUsrName.Enabled = False txtPass.Enabled = False txtconfirm.Enabled = False Frame2.Enabled = False End Sub Private Sub Enable_fields() Frame2.Enabled = True txtUsrName.Enabled = True txtPass.Enabled = True txtconfirm.Enabled = True txtUsrName.Text = "" txtPass.Text = "" CheckM.Value = 0 CheckD.Value = 0 End Sub Private Function Encrypt_password() As String Dim strpw As String Dim s As String Dim c As Integer Dim intIndex As Integer Dim strArray(10) As String Dim strFinal As String strpw = txtPass.Text 'gets the leftmost character strpw = txtPass.Text For intIndex = 1 To Len(strpw) s = Mid(strpw, intIndex, 1) 'encrypt the password c = Asc(s) + 5 strArray(intIndex) = Chr(c) 'append the character to the final string strFinal = strFinal + strArray(intIndex) Next intIndex Encrypt_password = strFinal End Function Private Sub txtPass_Validate(Cancel As Boolean) If Len(txtPass.Text) < 6 Or Len(txtPass.Text) > 10 Then MsgBox "Password should be minimum 6 characters and not more than 10 characters", vbExclamation, "Error" txtPass.SetFocus SendKeys "{Home}+{End}" Cancel = True End If End Sub
446
Chapter 11
447
448
Chapter 11
Set rstId = New Recordset rstId.Open "Select id from Users where id = " & "'" & strUsername & "'" & "And passwd =" & "'" & strPasswd & "'", DB, adOpenStatic, adLockOptimistic If rstId.EOF Then RecStatus = False 'Invalid user Else RecStatus = True 'User found End If End Function Private Sub Form_Load() Set DB = New Connection DB.Open "DSN=Elective;UID=scott;password=tiger;" End Sub Private Function Encrypt_password() As String Dim strpw As String Dim s As String Dim c As Integer Dim intIndex As Integer Dim strArray(10) As String Dim strFinal As String strpw = txtPassword.Text 'gets the leftmost character strpw = txtPassword.Text For intIndex = 1 To Len(strpw) s = Mid(strpw, intIndex, 1) 'encrypt the password c = Asc(s) + 5 strArray(intIndex) = Chr(c) 'append the character to the final string strFinal = strFinal + strArray(intIndex) Next intIndex Encrypt_password = strFinal End Function
PART - II
11.2 TUTORIAL USING MS-Access & VB6.0
All the examples shown in Part-I used Oracle9i as back-end. Let us show an example with MS-Access as back-end in this section. However, we shall retain the front-end as VB6.0 only. The design using MS-Access is not much different from Tutorial-I of Part-I. All that we need to do is to change the code in the FormLoad section as given below:
Private Sub Form_Load()
449
'On Error Resume Next Set DB = New Connection 'For MS-Access Databse use the following connection 'DB.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\DBMS\TutorialI\Demo.mdb;Mode=ReadWrite|Share Deny None;Persist Security Info=False" 'Create recordset object Set rstStudent = New Recordset rstStudent.Open "Select * from Test", DB, adOpenDynamic, adLockOptimistic 'Bind the form controls to database fields Set txtRegNo.DataSource = rstStudent txtRegNo.DataField = "RegNo" Set txtName.DataSource = rstStudent txtName.DataField = "Name" End Sub
The database file Demo.mdb with the table name 'Test' should be created in MSAcces with the same set of attributes as shown earlier. The above code (bold letters) is a partial one and it is assumed to be in the folder: D:\DBMS\Tutorial-I. The rest of the code is same as Tutorial-I. You don't need to change anything else at all.
PART - III
11.3 TUTORIAL USING SQL Server & VB6.0
The Tutorials given in the earlier sections did not cover a very important control called "FlexGrid". The purpose of this section is to include the FlexGrid control and demonstrate its usage in a typical application. Let us adopt the same procedure as we did for the other tutorials too. However, one major change that we introduce in this example is use of SQL Server 2000 as the backend database instead of Oracle 9i. The objective of this application is to create a simple table called "Product" in SQL Server and add data records using a flex grid control. Let us make things clear! Hither to, we have used many text boxes and/or combo boxes to enter the data. In addition, at any point of time we could add only one record. Now, using this small application we will be able to add as many records as needed and save all of them at one go. We shall implement this using the flex grid control of VB 6.0.
450
Chapter 11
Step-2: Step-3:
Fig. 11. 11 Data entry form for Product table with a FlexGrid Control
Notice that the form has three text boxes and a combo box. In addition, we have a flexgrid called "Grid1" where multiple data records be added. You can notice also that every time a
451
new record is added, by pressing "Add" button, the partial sum is shown in a label box against "Total". Step-4: After creating the layout with various controls, type the code for each button and Form Load section as given below: Option Explicit Dim cn As ADODB.Connection Dim rstemp As New ADODB.Recordset Dim rsgrn As New ADODB.Recordset Dim Sum As Double 'to compute partial sum Private Sub Form_Load() Call initgrid Set cn = New ADODB.Connection 'The back end used is SQL Server 'change the user name and password for your settings cn.Open "DSN=T1;UID=sa;PASSWORD=bit" 'populate the combo box cmbCode.AddItem (100) cmbCode.AddItem (200) cmbCode.AddItem (300) cmbCode.AddItem (400) cmbCode.AddItem (500) cmbCode.AddItem (600) lblDate.Caption = Date Grid1.Col = 0 Grid1.row = 0 'form sizing Me.Height = 6850 Me.Width = 9270 cmbCode.Visible = True End Sub Public Sub initgrid() Dim s As String s$ = "<SR_NO|Product ID|Description|Unit|Quantity|Price|Net Price" Grid1.FormatString = s$ Grid1.ColWidth(1) = 1200 Grid1.ColWidth(2) = 2000 Grid1.ColWidth(3) = 800 Grid1.ColWidth(4) = 1000 Grid1.ColWidth(5) = 1000 Grid1.ColWidth(6) = 1370 Grid1.ColAlignment(4) = 7 Grid1.ColAlignment(5) = 7 Grid1.ColAlignment(6) = 7 Grid1.Rows = 2 End Sub
452
Chapter 11
Private Sub cmdAdd_Click() If txtprice.Text <> "" And txtqty.Text <> "" And cmbCode.Text <> "" Then If IsNumeric(txtprice.Text) And IsNumeric(txtqty.Text) Then ' add to the grid Dim row As Integer row = Grid1.Rows - 1 Grid1.TextMatrix(row, 0) = row Grid1.TextMatrix(row, 1) = cmbCode.Text Grid1.TextMatrix(row, 2) = txtName.Text Grid1.TextMatrix(row, 3) = "Ltr" Grid1.TextMatrix(row, 4) = txtqty.Text Grid1.TextMatrix(row, 5) = txtprice.Text Grid1.TextMatrix(row, 6) = Format((Val(txtqty.Text) * Val(txtprice.Text)), ".00") 'Display the partial total Sum = Sum + (Val(txtqty.Text) * Val(txtprice.Text)) lblTotal.Caption = Sum Grid1.Rows = Grid1.Rows + 1 cmbCode.Text = "" txtName.Text = "" txtqty.Text = "" txtprice.Text = "" cmbCode.SetFocus Else MsgBox "Invalid data", vbCritical End If Else MsgBox "No data in the fields", vbCritical End If Exit Sub databaseerror: cn.RollbackTrans rsgrn.Close MsgBox "The following error has occured while saving data : " & Chr(13) + Chr(10) & " No : " & Err.Number & " Description : " & Err.Description End Sub Private Sub cmdSave_Click() Dim i As Integer 'whole grid is empty If Grid1.Rows < 3 Or Grid1.TextMatrix(1, 1) = "" Then MsgBox "There is no record to save" Exit Sub End If On Error GoTo databaseerror 'start saving Set rsgrn = New ADODB.Recordset rsgrn.Open "select * from Product", cn, adOpenDynamic, adLockOptimistic 'start transaction cn.BeginTrans
453
For i = 1 To Grid1.Rows - 2 rsgrn.AddNew rsgrn.Fields("grnno") = Val(Grid1.TextMatrix(i, 1)) rsgrn.Fields("pcode") = Grid1.TextMatrix(i, 2) rsgrn.Fields("value") = Val(Grid1.TextMatrix(i, 3)) rsgrn.Fields("quantity") = Val(Grid1.TextMatrix(i, 4)) rsgrn.Update Next i 'commit transaction to save changes cn.CommitTrans MsgBox "The data has been saved successfully", vbInformation, "FMC United" rsgrn.Close Grid1.Clear Call initgrid 'txtgrn.Text = Val(txtgrn.Text) + 1 cmbCode.SetFocus Sum = 0 lblTotal.Caption = Sum Exit Sub databaseerror: cn.RollbackTrans rsgrn.Close MsgBox "The following error has occured while saving data : " & Chr(13) + Chr(10) & " No : " & Err.Number & " Description : " & Err.Description End Sub Private Sub cmdCancel_Click() Unload Me End Sub Private Sub cmdClear_Click() Grid1.Clear Grid1.Rows = 2 cmbCode.SetFocus End Sub
PART - IV
11.4 COMPANY DATABASE
Though there are many problems for automation, we have selected a very simple problem called the Company Database. This problem has been discussed already in Chapter 1; but now we shall describe its implementation issues. Following is a simple abstract of the problem domain for the Company database.
454
Chapter 11
1. Let us assume that our Company wants to automate its entire administration work. 2. The Company has many employees working in various departments. Each employee has SSN, Name, Address, Sex, Salary, etc. 3. It has several departments. Each department has a manager who is also an employee of the company. A department may be located at more than one place. 4. Every department controls one or more projects. 5. Projects are identified by Project Number, Project Name, and so on. 6. An employee is allowed to work for a particular department. However, he or she can work on more than one project. 7. Salary is paid to employees depending upon how many hours they work on project(s). 8. Employees may have more than one dependents and it is required that their information also must be stored in the database. Since maintaining all these information manually becomes cumbersome, the company wishes to automate the entire process. For this case study, we prefer to use Oracle9i and VB 6.0 because of their popularity in the industry and their rich GUI capabilities.
455
CREATE TABLE Employee ( SSN char(9) not null, Name varchar2(20) not null, BDate date, Address varchar2(30), Sex char, Salary number(10,2), SuperSSN char(9), Primary Key(SSN) ); CREATE TABLE Department ( DNumber number(2) not null, DName varchar2(10) not null, MgrSSN char(9), MgrStartDate date, Primary Key(DNumber), foreign key(MgrSSN) references Employee(SSN) on delete cascade ); ALTER TABLE Employee ADD DNo number(4) not null references Department(DNumber) on delete cascade; CREATE TABLE Project ( PNumber number(2) not null, PName varchar(10) not null, Plocation varchar2(15), DNum number(2) not null, Primary Key(PNumber), Unique(PName), foreign key(DNum) references Department(DNumber) on delete cascade ); CREATE TABLE Dependent ( ESSN char(9) not null, Dependent_Name varchar2(15) not null, Sex char, BDate date, Relationship varchar2(10), Primary Key(ESSN, Dependent_Name), foreign key(ESSN) references Employee(SSN) on delete cascade ); CREATE TABLE Dept_Locations ( DNumber number(2) not null, Dlocation varchar2(15),
456
Primary Key(DNumber, Dlocation), foreign key(DNumber) references Department(DNumber) on delete cascade ); CREATE TABLE Works_On ( ESSN char(9) not null, PNo number(2) not null, Hours number(3,1) not null, Primary Key(ESSN, PNo), foreign key(ESSN) references Employee(SSN) on delete cascade, foreign key(PNo) references Project(PNumber) on delete cascade ); CREATE VIEW SSNHrs as SELECT ESSN, Sum(Hours) as TotalHrs FROM Works_On GROUP BY ESSN; COMMIT;
Chapter 11
457
Step-3:
458
Chapter 11
With this step, you have successfully created a new data source name called "empl" for Oracle ODBC.
459
application with some assigned privileges. In case if it does not match the login screen, the login window should appear again. With this requirement in mind, we shall show how to create the login form. The necessary steps are shown below:
Step-1: Create a new Login form with name as "frmLogin" and caption property set to "login". The controls are as shown in Figure 11.15.
460
'clear the field txtPassword.Text = "" End Sub
Chapter 11
Employee Details
Ctrl+N Ctrl+Q
F2
461
Figure 11.17 shows the "frmMainForm" and its Picture property is set with the bitmap image.
462
frmEmployee.Show vbModal End Sub Private Sub mnuDept_Click() frmDept.Show vbModal End Sub Private Sub mnudeploc_Click() frmDepLoc.Show vbModal End Sub Private Sub mnuepl_Click() frmEmployee.Show vbModal End Sub Private Sub mnuproj_Click() frmProject.Show vbModal End Sub Private Sub mnuRDept_Click() rptDepartment.Show vbModal End Sub Private Sub mnuREmp_Click() rptEmployee.Show vbModal End Sub Private Sub mnuREmpWages_Click() Dim choice As Integer If DataEnvironment1.rscmdWages.State = adStateOpen Then DataEnvironment1.rscmdWages.Close End If choice = InputBox("Please enter the Wages/Hour") DataEnvironment1.cmdWages Val(choice) Load rptWages rptWages.Show vbModal End Sub Private Sub mnuRProject_Click() rptProject.Show vbModal End Sub Private Sub mnuwrks_Click() frmWorks.Show vbModal End Sub Step-3: Save the "frmMainForm" and do not execute!
Chapter 11
463
can add, delete, modify, search, add dependent details, and many more. These tasks can be achieved either by clicking the drop down menus or the tool bar icons. Below are the steps needed to create the Employee form.
Step-1: Click Project > Add Form. Draw various controls as indicated in Figure 11.18
Step-3: Step-4:
464
Load rptDependent rptDependent.Show vbModal End Sub
Chapter 11
Private Sub mnuDelete_Click() Dim ChoiceSSN As String Dim Response As Integer Dim strSQL As String Response = MsgBox("Are you sure you want to Delete?", vbYesNo, "Confirm Deletion") If Response = vbYes Then DataGrid1.AllowDelete = True ChoiceSSN = DataGrid1.Columns(1) strSQL = "Delete from Employee where SSN = " & ChoiceSSN db.Execute strSQL Call Reset DataGrid1.AllowDelete = False End If End Sub Private Sub mnuExit_Click() Unload Me End Sub Private Sub mnuModify_Click() strSSN = DataGrid1.Columns(1) frmModifyEmp.Show vbModal Call Reset End Sub Private Sub mnuName_Click() Dim ChoiceName As String ChoiceName = InputBox("Type the Employee's Name", "Search by Name...") ChoiceName = StrConv(ChoiceName, vbUpperCase) If ChoiceName <> "" Then 'user has pressed OK button 'cancel button returns empty string Set rstEmpFind = New Recordset rstEmpFind.CursorLocation = adUseClient rstEmpFind.Open "Select * from Employee where Name = " & "'" & ChoiceName & "'", db, adOpenStatic, adLockReadOnly If rstEmpFind.EOF Then MsgBox "Employee does not exist", vbCritical, "Employee Not Found" Else Set DataGrid1.DataSource = rstEmpFind DataGrid1.Refresh End If End If End Sub Private Sub mnuNew_Click() frmAddEmployee.Show vbModal End Sub Private Sub mnuOpenDep_Click() frmDepen.Show vbModal End Sub
465
Private Sub mnuRefresh_Click() Set DataGrid1.DataSource = rstEmployee DataGrid1.Refresh End Sub Private Sub mnuSSN_Click() Dim ChoiceSSN As String ChoiceSSN = InputBox("Enter the SSN") If ChoiceSSN <> "" Then 'user has pressed OK button 'cancel button returns empty string Set rstEmpFind = New Recordset rstEmpFind.CursorLocation = adUseClient rstEmpFind.Open "Select * from Employee where SSN = " & "'" & ChoiceSSN & "'", db, adOpenStatic, adLockReadOnly If rstEmpFind.EOF Then MsgBox "Employee does not exist", vbCritical, "Employee Not Found" Else Set DataGrid1.DataSource = rstEmpFind DataGrid1.Refresh End If End If End Sub Private Sub Toolbar1_ButtonClick(ByVal Button As MSComCtlLib.Button) On Error Resume Next Select Case Button.Key Case "voc" 'ToDo: Add 'voc' button code. 'MsgBox "Add 'voc' button code." Case "Redo" 'rstEmployee.MoveFirst Set DataGrid1.DataSource = rstEmployee DataGrid1.Refresh Exit Sub Errorhandler: MsgBox "Error....", vbExclamation, "Error" Case "Undo" 'ToDo: Add 'Undo' button code. 'MsgBox "Add 'Undo' button code." Case "New" frmAddEmployee.Show vbModal Call Reset Case "Open" mnuOpenDep_Click Case "Save" 'ToDo: Add 'Save' button code. 'MsgBox "Add 'Save' button code." Case "Delete" mnuDelete_Click Case "Find" mnuSSN_Click Case "Help" 'ToDo: Add 'Help' button code. 'MsgBox "Add 'Help' button code." End Select
466
End Sub
Chapter 11
Private Sub Form_Load() 'The user is a clerk - no access to delete button If frmLogin.LoginSucceeded = 2 Then mnuDelete.Enabled = False 'Remove the Delete (index is 6) button Toolbar1.Buttons.Item(6).Enabled = False End If Set db = New Connection db.Open "DSN=EMPL;UID=SCOTT;PASSWORD=TIGER;" Set rstEmployee = New Recordset rstEmployee.CursorLocation = adUseClient rstEmployee.Open "Select * from Employee order by TO_NUMBER(SSN)", db, adOpenStatic, adLockReadOnly Set DataGrid1.DataSource = rstEmployee DataGrid1.Refresh End Sub Private Sub Reset() Set rstEmployee = New Recordset rstEmployee.CursorLocation = adUseClient rstEmployee.Open "Select * from Employee order by TO_NUMBER(SSN)", db, adOpenStatic, adLockReadOnly Set DataGrid1.DataSource = rstEmployee DataGrid1.Refresh End Sub
467
The Figure 11.19 shows the form with these controls and the labels.
468
Chapter 11
MsgBox "Date of birth exceeds the current date", vbCritical, "Error in Birth date" cboDay.SetFocus strDate = cboDay.Text + "/" + cboMonth.Text + "/" + cboYear.Text End If Exit Sub err1: MsgBox Err.Description + Chr(13) + Chr(10) + "One or more fields may be empty", vbCritical, "Error" End Sub Private Sub cmdCancel_Click() 'Cancels the changes done to new record rstEmployee.CancelUpdate Unload Me End Sub Private Sub Form_Load() Set db = New Connection db.Open "DSN=EMPL;UID=SCOTT;PASSWORD=TIGER;" Set rstEmployee = New Recordset rstEmployee.CursorLocation = adUseClient rstEmployee.Open "Select * from Employee", db, adOpenDynamic, adLockOptimistic rstEmployee.AddNew txtSSN.Text = "" txtName.Text = "" txtAddr.Text = "" txtSalary.Text = "" cboSSSN.Text = "" cboDNo.Text = "" 'populate Department Number Set rstDept = New Recordset rstDept.Open "Select DNumber from Department", db, adOpenStatic, adLockReadOnly While Not rstDept.EOF cboDNo.AddItem rstDept!DNumber rstDept.MoveNext Wend 'populate supervisor SSN Set rstSuperSSN = New Recordset rstSuperSSN.Open "Select SSN from Employee ", db, adOpenStatic, adLockReadOnly While Not rstSuperSSN.EOF cboSSSN.AddItem rstSuperSSN!SSN rstSuperSSN.MoveNext Wend 'set default value cboSex.Text = "M" 'Populate Day Dim intDay As Integer intDay = 1 While intDay <= 31 cboDay.AddItem intDay intDay = intDay + 1 Wend
469
'Populate Month cboMonth.AddItem "Jan" cboMonth.AddItem "Feb" cboMonth.AddItem "Mar" cboMonth.AddItem "Apr" cboMonth.AddItem "May" cboMonth.AddItem "Jun" cboMonth.AddItem "Jul" cboMonth.AddItem "Aug" cboMonth.AddItem "Sep" cboMonth.AddItem "Oct" cboMonth.AddItem "Nov" cboMonth.AddItem "Dec" 'Populate Year Dim intYear As Integer Dim strYear As String Dim intY As Integer intYear = 1947 strYear = Right(Format(Date, "dd/mm/yyyy"), 4) intY = Val(strYear) While intY >= intYear cboYear.AddItem intY intY = intY - 1 Wend End Sub Private Sub txtAddr_Validate(Cancel As Boolean) txtAddr.Text = StrConv(txtAddr.Text, vbUpperCase) If txtAddr.Text = "" Then MsgBox "Incomplete or blank field not allowed!", vbCritical + vbOKOnly, "ERROR" Cancel = True End If End Sub Private Sub txtSalary_Validate(Cancel As Boolean) If Not IsNumeric(txtSalary.Text) Or txtSalary.Text = "" Then MsgBox "Only numbers are allowed!", vbCritical + vbOKOnly, "ERROR" Cancel = True End If End Sub Private Sub txtSSN_Validate(Cancel As Boolean) 'txtSSN.Text = StrConv(txtSSN.Text, vbUpperCase) If txtSSN.Text = "" Then MsgBox "Blank field not allowed. Enter valid SSN", vbCritical + vbOKOnly, "ERROR" Cancel = True ElseIf Len(txtSSN.Text) > 9 Then MsgBox "Enter SSN not more than 9 Characters", vbCritical + vbOKOnly, "ERROR" Cancel = True End If End Sub
470
Chapter 11
Private Sub txtName_Validate(Cancel As Boolean) txtName.Text = StrConv(txtName.Text, vbUpperCase) If txtName.Text = "" Then MsgBox "Name field empty", vbCritical + vbOKOnly, "VALIDATION" Cancel = True ElseIf IsNumeric(txtName.Text) Then MsgBox "Only Characters are allowed", vbCritical + vbOKOnly, "ERROR" Cancel = True ElseIf Len(txtName.Text) > 20 Then MsgBox "Name exceeds 20 Characters", vbCritical + vbOKOnly, "VALIDATION" Cancel = True End If End Sub Private Sub cboDNo_Validate(Cancel As Boolean) If cboDNo.ListIndex = -1 Then MsgBox "Select the Department No.", vbCritical, "Missing data" Cancel = True End If End Sub Step-4: Similar to "frmAddEmployee", create a new form for the Dependents and name it as "frmDepen". The structure of the form is shown Figure 11.20. Type the code as shown below: Option Explicit Dim db As Connection Dim rstEmployee As Recordset Dim rstDepend As Recordset Dim rstBrowse As Recordset Private Sub cboESSN_Validate(Cancel As Boolean) If cboESSN.ListIndex = -1 Then MsgBox "Select the Employee SSN", vbCritical, "Missing data" Cancel = True End If End Sub
Step-5:
471
Image1 cboEmpSSN
Fig. 11.20 Dependent Form (Arrows indicate the name of the controls)
Private Sub cboRelation_Validate(Cancel As Boolean) If cboRelation.ListIndex = -1 Then MsgBox "Select the Relationship", vbCritical, "Missing data" Cancel = True End If End Sub Private Sub cmdAdd_Click() On Error GoTo err1 rstDepend("Dependent_Name") = txtName.Text rstDepend("ESSN") = cboESSN.Text rstDepend("BDate") = txtBdate.Text rstDepend("Sex") = cboSex.Text rstDepend("Relationship") = cboRelation.Text rstDepend.Update
472
Frame2.Enabled = True Unload Me Exit Sub err1: MsgBox Err.Description Frame2.Enabled = True End Sub Private Sub cmdCancel_Click() rstDepend.CancelUpdate Frame2.Enabled = True Frame1.Enabled = False End Sub Private Sub cmdClose_Click() Unload Me End Sub
Chapter 11
Private Sub cmdDelete_Click() On Error GoTo err1 Dim ChoiceSSN As String Dim Response As Integer Dim strSQL As String Response = MsgBox("Are you sure you want to Delete?", vbYesNo, "Confirm Deletion") If Response = vbYes Then DataGrid1.AllowDelete = True ChoiceSSN = DataGrid1.Columns(0) strSQL = "Delete from Dependent where ESSN = " & ChoiceSSN db.Execute strSQL Call Reset DataGrid1.AllowDelete = False End If err1: MsgBox Err.Description End Sub Private Sub Form_Load() Set db = New Connection db.Open "DSN=EMPL;UID=SCOTT;PASSWORD=TIGER;" Set rstDepend = New Recordset rstDepend.CursorLocation = adUseClient rstDepend.Open "Select * from Dependent", db, adOpenDynamic, adLockOptimistic Set rstEmployee = New Recordset rstEmployee.CursorLocation = adUseClient rstEmployee.Open "Select * from Employee", db, adOpenDynamic, adLockOptimistic 'populate the SSN combo box While Not rstEmployee.EOF cboESSN.AddItem (rstEmployee!SSN) cboEmpSSN.AddItem (rstEmployee!SSN) rstEmployee.MoveNext Wend 'Create a new empty record
473
rstDepend.AddNew txtName.Text = "" txtBdate.Text = "" cboESSN.Text = "Select SSN" cboRelation = "Select the Relationship" cboRelation.AddItem "Wife" cboRelation.AddItem "Husband" cboRelation.AddItem "Son" cboRelation.AddItem "Daughter" cboRelation.AddItem "Mother" cboRelation.AddItem "Father" Image1.ToolTipText = "Browse" cboSex.Text = "M" Frame2.Enabled = False End Sub Private Sub Image1_Click() If cboEmpSSN.Text <> "" Then Set rstBrowse = New Recordset rstBrowse.CursorLocation = adUseClient rstBrowse.Open "Select * from Dependent where ESSN = " & "'" & cboEmpSSN.Text & "'", db, adOpenStatic, adLockReadOnly Set DataGrid1.DataSource = rstBrowse DataGrid1.Refresh Else MsgBox "No Employee selected", vbExclamation, "Error" End If End Sub Private Sub Reset() Set rstBrowse = New Recordset rstBrowse.CursorLocation = adUseClient rstBrowse.Open "Select * from Dependent", db, adOpenStatic, adLockReadOnly Set DataGrid1.DataSource = rstBrowse DataGrid1.Refresh End Sub Private Sub txtBdate_Validate(Cancel As Boolean) Dim UsrDate As Date Dim CurrentDate As Date UsrDate = Format(txtBdate.Text, "dd/mmm/yyyy") 'convert string to date CurrentDate = Format(Now, "dd/mmm/yyyy") 'convert string to date If UsrDate >= CurrentDate Then MsgBox "Birth date is greater than current date", vbCritical, "Error in birth date" txtBdate.SelStart = 0 txtBdate.SelLength = Len(txtBdate.Text) Cancel = True End If End Sub Private Sub txtName_Validate(Cancel As Boolean) txtName.Text = StrConv(txtName.Text, vbUpperCase) If txtName.Text = "" Then
474
Chapter 11
MsgBox "Name field empty", vbCritical + vbOKOnly, "VALIDATION" Cancel = True ElseIf IsNumeric(txtName.Text) Then MsgBox "Only Characters are allowed", vbCritical + vbOKOnly, "ERROR" Cancel = True ElseIf Len(txtName.Text) > 20 Then MsgBox "Name exceeds 20 Characters", vbCritical + vbOKOnly, "VALIDATION" Cancel = True End If End Sub Step-6: One more work is remaining before we conclude this section. That is nothing but to create yet another form for modifying the employee data. Hence, simply create a new form just similar to "frmAddEmployee" form. However, the code will be different for this form. You must give "frmModifyEmp" for the name property and save the form with this name. The layout is shown in Figure 11.21.
475
Private Sub cboSSSN_Validate(Cancel As Boolean) If cboSSSN.ListIndex = -1 Then MsgBox "You must select the supervisor" Cancel = True End If End Sub Private Sub cmdCancel_Click() Unload Me End Sub Private Sub cmdUpdate_Click() Dim strSQL As String strSQL = "Update Employee Set SSN = " & "'" & txtSSN.Text & "'" & " Where SSN = " & "'" & frmEmployee.strSSN & "'" db.Execute strSQL strSQL = "Update Employee Set Name = " & "'" & txtName.Text & "'" & " Where SSN = " & "'" & frmEmployee.strSSN & "'" db.Execute strSQL strSQL = "Update Employee set Address = " & "'" & txtAddr.Text & "'" & " Where SSN = " & "'" & frmEmployee.strSSN & "'" db.Execute strSQL strSQL = "Update Employee set Sex = " & "'" & cboSex.Text & "'" & " Where SSN = " & "'" & frmEmployee.strSSN & "'" db.Execute strSQL strSQL = "Update Employee set Salary = " & Val(txtSalary.Text) & " Where SSN = " & "'" & frmEmployee.strSSN & "'" db.Execute strSQL strSQL = "Update Employee set SuperSSN = " & "'" & cboSSSN.Text & "'" & " Where SSN = " & "'" & frmEmployee.strSSN & "'" db.Execute strSQL strSQL = "Update Employee set DNo = " & Val(cboDNo.Text) & " Where SSN = " & "'" & frmEmployee.strSSN & "'" db.Execute strSQL Unload Me End Sub Private Sub Form_Load() Dim SrchSSN As String SrchSSN = frmEmployee.strSSN Set db = New Connection db.Open "DSN=EMPL;UID=SCOTT;PASSWORD=TIGER;" Set rstEmployee = New Recordset rstEmployee.CursorLocation = adUseClient rstEmployee.Open "Select * from Employee where SSN = " & "'" & SrchSSN & "'", db, adOpenDynamic, adLockOptimistic Set rstDate = New Recordset rstDate.CursorLocation = adUseClient 'rstDate.Open "Select To_Char(BDate,'dd/mm/yyyy') as MyDate from Employee where SSN = " & "'" & SrchSSN & "'", db, adOpenDynamic, adLockOptimistic rstDate.Open "Select BDate from Employee where SSN = " & "'" & SrchSSN & "'", db, adOpenDynamic, adLockOptimistic 'Populate the form fields
476
txtSSN.Text = rstEmployee!SSN txtName.Text = rstEmployee!Name 'Extract Day, Month, and year Dim strDOB As String strDOB = Format$(rstDate!BDate, "dd,mmm,yyyy") 'strDOB = rstDate!MyDate cboDay.Text = Left(strDOB, 2) cboMonth.Text = Mid(strDOB, 4, 3) cboYear.Text = Right(strDOB, 4) txtAddr.Text = rstEmployee!Address cboSex.Text = rstEmployee!Sex txtSalary.Text = rstEmployee!Salary cboSSSN.Text = rstEmployee!SuperSSN cboDNo.Text = rstEmployee!DNo 'populate Department Number Set rstDept = New Recordset rstDept.Open "Select DNumber from Department", db, adOpenStatic, adLockReadOnly While Not rstDept.EOF cboDNo.AddItem rstDept!DNumber rstDept.MoveNext Wend 'populate supervisor SSN Set rstSuperSSN = New Recordset rstSuperSSN.Open "Select SSN from Employee ", db, adOpenStatic, adLockReadOnly While Not rstSuperSSN.EOF cboSSSN.AddItem rstSuperSSN!SSN rstSuperSSN.MoveNext Wend 'Populate Day Dim intDay As Integer intDay = 1 While intDay <> 32 cboDay.AddItem intDay intDay = intDay + 1 Wend 'Populate Month cboMonth.AddItem "Jan" cboMonth.AddItem "Feb" cboMonth.AddItem "Mar" cboMonth.AddItem "Apr" cboMonth.AddItem "May" cboMonth.AddItem "Jun" cboMonth.AddItem "Jul" cboMonth.AddItem "Aug" cboMonth.AddItem "Sep" cboMonth.AddItem "Oct" cboMonth.AddItem "Nov" cboMonth.AddItem "Dec"
Chapter 11
477
'Populate Year Dim intYear As Integer Dim strYear As String intYear = 1900 strYear = Right(Format(Date, "dd/mm/yyyy"), 4) While intYear <= Val(strYear) cboYear.AddItem intYear intYear = intYear + 1 Wend cboDay.Enabled = False cboMonth.Enabled = False cboYear.Enabled = False End Sub
cmdCanc el
cmdClose
cmdFirst
cmdPrev
cmdNext
cmdLast
478
Chapter 11
Give the name as "frmDept" and save the form with the same name. Now to create the tool bar, you can follow the below steps:
Step-1: Draw an Imagelist from the tool box (left side of your main VB window). The default name given to it will be "ImageList1". Right lick on the ImageList1 and select properties and select the Images tab (see Figure 11.23).
Step-2:
Step-4:
479
480
On Error Resume Next rstDept.MoveFirst cmdPrev.Enabled = False cmdNext.Enabled = True End Sub Private Sub cmdLast_Click() On Error Resume Next rstDept.MoveLast cmdNext.Enabled = False cmdPrev.Enabled = True End Sub Private Sub cmdNext_Click() On Error Resume Next rstDept.MoveNext If rstDept.EOF Then rstDept.MoveLast End If cmdPrev.Enabled = True End Sub Private Sub cmdPrev_Click() On Error Resume Next rstDept.MovePrevious If rstDept.BOF Then rstDept.MoveFirst End If cmdNext.Enabled = True Exit Sub End Sub
Chapter 11
'Dim rstBrowse As Recordset Private Sub Form_Load() Set db = New Connection db.Open "DSN=EMPL;UID=SCOTT;PASSWORD=TIGER;" Set rstDept = New Recordset rstDept.CursorLocation = adUseClient rstDept.Open "Select * from Department", db, adOpenDynamic, adLockOptimistic Set rstEmployee = New Recordset rstEmployee.CursorLocation = adUseClient rstEmployee.Open "Select * from Employee", db, adOpenDynamic, adLockOptimistic 'populate the Manager SSN combo box While Not rstEmployee.EOF cboMSSN.AddItem (rstEmployee!SSN) rstEmployee.MoveNext Wend 'Bind the form controls to database fields Set txtDNo.DataSource = rstDept txtDNo.DataField = "DNumber" Set txtDName.DataSource = rstDept txtDName.DataField = "DName"
481
Set cboMSSN.DataSource = rstDept cboMSSN.DataField = "MgrSSN" Set txtMDate.DataSource = rstDept txtMDate.DataField = "MgrStartDate" 'Disable Day, Month, and Year combo boxes cboDay.Visible = False cboMonth.Visible = False cboYear.Visible = False 'Populate Day Dim intDay As Integer intDay = 1 While intDay <> 32 cboDay.AddItem intDay intDay = intDay + 1 Wend 'Populate Month cboMonth.AddItem "Jan" cboMonth.AddItem "Feb" cboMonth.AddItem "Mar" cboMonth.AddItem "Apr" cboMonth.AddItem "May" cboMonth.AddItem "Jun" cboMonth.AddItem "Jul" cboMonth.AddItem "Aug" cboMonth.AddItem "Sep" cboMonth.AddItem "Oct" cboMonth.AddItem "Nov" cboMonth.AddItem "Dec" 'Populate Year Dim intYear As Integer intYear = 2005 While intYear >= 1947 cboYear.AddItem intYear intYear = intYear - 1 Wend If rstDept.RecordCount = 0 Then MsgBox "Department Table is Empty", vbCritical, "Error" cmdFirst.Enabled = False cmdPrev.Enabled = False cmdNext.Enabled = False cmdLast.Enabled = False End If End Sub Private Sub Toolbar1_ButtonClick(ByVal Button As MSComCtlLib.Button) On Error GoTo err1 Select Case Button.Key Case "Close" Unload Me
482
Case "New" rstDept.AddNew 'Create a new record and clear cmdFirst.Enabled = False cmdPrev.Enabled = False cmdNext.Enabled = False cmdLast.Enabled = False txtMDate.Visible = False cboDay.Visible = True cboMonth.Visible = True cboYear.Visible = True txtDNo.Text = "" txtDName.Text = "" cboMSSN.Text = "" cboDay.Text = "" cboMonth.Text = "" cboYear.Text = "" txtDNo.SetFocus Case "Save" 'On Error GoTo err1 Dim strDate As String rstDept!DNumber = txtDNo.Text rstDept!DName = txtDName.Text If cboMSSN.Text = "" Then
Chapter 11
rstDept!MgrSSN = Null Else rstDept!MgrSSN = cboMSSN.Text End If strDate = cboDay.Text + "/" + cboMonth.Text + "/" + cboYear.Text rstDept!MgrStartDate = strDate rstDept.Update cmdFirst.Enabled = True cmdPrev.Enabled = True cmdNext.Enabled = True cmdLast.Enabled = True cboDay.Visible = False cboMonth.Visible = False cboYear.Visible = False txtMDate.Visible = True rstDept.Requery Case "Undo" cmdCancel_Click Case "Delete" On Error Resume Next Dim intChoice If Not txtDNo = "" Then If Not rstDept.EOF Then intChoice = MsgBox("Are you sure that you want to delete?", vbYesNo + vbCritical) If intChoice = vbYes Then rstDept.Delete rstDept.MoveNext If rstDept.EOF Then
483
rstDept.MoveLast End If End If End If Else MsgBox "No Record to Delete", vbExclamation End If End Select Exit Sub err1: MsgBox Err.Description End Sub Private Sub cmdClose_Click() Unload Me End Sub
484
Private Sub cmdNext_Click() On Error Resume Next rstProject.MoveNext If rstProject.EOF Then rstProject.MoveLast End If cmdPrev.Enabled = True End Sub
Chapter 11
485
Set rstDept = New Recordset rstDept.CursorLocation = adUseClient rstDept.Open "Select * from Department", db, adOpenDynamic, adLockOptimistic 'populate the Dept Number combo box While Not rstDept.EOF cboDNum.AddItem (rstDept!DNumber) rstDept.MoveNext Wend 'Bind the form controls to database fields Set txtPNo.DataSource = rstProject txtPNo.DataField = "PNumber" Set txtPName.DataSource = rstProject txtPName.DataField = "PName" Set cboPLoc.DataSource = rstProject cboPLoc.DataField = "PLocation" Set cboDNum.DataSource = rstProject cboDNum.DataField = "DNum" 'populate Project locations combo box cboPLoc.AddItem "Bangalore" cboPLoc.AddItem "Chennai" cboPLoc.AddItem "New Delhi" cboPLoc.AddItem "Mumbai" cboPLoc.AddItem "Kolkota" cboPLoc.AddItem "Coimbatore" cboPLoc.AddItem "Pune" cboPLoc.AddItem "Belgaum" cboPLoc.AddItem "Mysore" End Sub Private Sub Toolbar1_ButtonClick(ByVal Button As MSComCtlLib.Button) On Error GoTo err1 Select Case Button.Key Case "Close" Unload Me Case "New" rstProject.AddNew 'Create a new record and clear cmdFirst.Enabled = False cmdPrev.Enabled = False cmdNext.Enabled = False cmdLast.Enabled = False txtPNo.Text = "" txtPName.Text = "" cboPLoc = "" cboDNum.Text = "" txtPNo.SetFocus 'disable New button and Delete button Toolbar1.Buttons.Item(2).Enabled = False Toolbar1.Buttons.Item(5).Enabled = False
486
Chapter 11
Case "Save" On Error GoTo err1 rstProject!PNumber = Val(txtPNo.Text) rstProject!PName = txtPName.Text rstProject!PLocation = cboPLoc.Text rstProject!DNum = cboDNum.Text rstProject.Update cmdFirst.Enabled = True cmdPrev.Enabled = True cmdNext.Enabled = True cmdLast.Enabled = True rstProject.Requery Toolbar1.Buttons.Item(2).Enabled = True Toolbar1.Buttons.Item(5).Enabled = True Case "Undo" cmdCancel_Click Case "Delete" On Error Resume Next Dim intChoice If Not rstProject.EOF Then intChoice = MsgBox("Are you sure that you want to delete?", vbYesNo + vbCritical) If intChoice = vbYes Then rstProject.Delete rstProject.MoveNext If rstProject.EOF Then rstProject.MoveLast End If End If End If End Select Exit Sub err1: MsgBox "The following Error has occured: " + Err.Description End Sub Private Sub cmdClose_Click() Unload Me End Sub Private Sub txtPNo_KeyPress(KeyAscii As Integer) If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then KeyAscii = 0 End If End Sub
487
records, we shall use a FlexGrid to obtain all the records (maximum is say 3) and save together in the database.
Step-1: Step-2: Go to Project > Add Form > Form, then click Open. Draw the controls as indicated in the Figure 11.26.
Control Frame Combo Box Combo Box Command Button Frame MSFlexGrid Command Button Command Button
Name Frame1 cboDeptNo cboDeptLoc cmdAdd Add Frame2 Grid1 cmdSave cmdCancel
488
Chapter 11
To add the FlexGrid control to the toolbox, click Ctrl+T and select Microsoft FlexGrid Control 6.0) and press "OK". Step-3: Type the following program, for each control shown in the above figure. Option Explicit Dim db As Connection Dim rstTemp As Recordset Dim rstDept As Recordset Private Sub cmdAdd_Click() Dim row As Integer If cboDeptNo.ListIndex <> -1 And cboDeptLoc.ListIndex <> -1 Then row = Grid1.Rows - 1 Grid1.TextMatrix(row, 0) = row Grid1.TextMatrix(row, 1) = cboDeptNo.Text Grid1.TextMatrix(row, 2) = cboDeptLoc.Text Grid1.Rows = Grid1.Rows + 1 cboDeptNo.Text = "" cboDeptLoc.Text = "" cboDeptNo.SetFocus Else MsgBox "No data in the Fields" & Chr(13) + Chr(10) & "Select Dept. No and Location" cboDeptNo.SetFocus End If End Sub Private Sub cmdCancel_Click() Unload Me End Sub Private Sub cmdSave_Click() Dim i As Integer 'whole grid is empty If Grid1.Rows < 3 Then MsgBox "There is no record to save" Exit Sub End If On Error GoTo DatabaseError 'start saving Set rstTemp = New Recordset rstTemp.Open "select * from Dept_Locations", db, adOpenDynamic, adLockOptimistic 'start transaction db.BeginTrans For i = 1 To Grid1.Rows - 2 rstTemp.AddNew rstTemp.Fields("DNumber") = Val(Grid1.TextMatrix(i, 1)) rstTemp.Fields("DLocation") = Grid1.TextMatrix(i, 2) rstTemp.Update Next i 'commit transaction to save changes db.CommitTrans
489
MsgBox "The data has been saved successfully", vbInformation, "FMC United" Grid1.Clear Call InitGrid cboDeptNo.SetFocus Exit Sub DatabaseError: db.RollbackTrans MsgBox "The following error has occured while saving data : " & Chr(13) + Chr(10) & " No : " & Err.Number & " Description : " & Err.Description Grid1.Clear Call InitGrid cboDeptNo.SetFocus End Sub Private Sub Form_Load() Call InitGrid Set db = New Connection db.Open "DSN=EMPL;UID=SCOTT;PASSWORD=TIGER;" Set rstDept = New Recordset rstDept.CursorLocation = adUseClient rstDept.Open "Select * from Department", db, adOpenDynamic, adLockOptimistic 'populate the dept. no. combo box While Not rstDept.EOF cboDeptNo.AddItem (rstDept!DNumber) rstDept.MoveNext Wend 'populate dept. locations combo box cboDeptLoc.AddItem "Bangalore" cboDeptLoc.AddItem "Chennai" cboDeptLoc.AddItem "New Delhi" cboDeptLoc.AddItem "Mumbai" cboDeptLoc.AddItem "Kolkota" cboDeptLoc.AddItem "Coimbatore" cboDeptLoc.AddItem "Pune" cboDeptLoc.AddItem "Belgaum" cboDeptLoc.AddItem "Mysore" End Sub Public Sub InitGrid() Dim s As String Grid1.BackColorFixed = vbCyan s$ = "<SR_NO|Dept. No.|Dept. Locations" Grid1.FormatString = s$ Grid1.ColWidth(1) = 1200 Grid1.ColWidth(2) = 2000 Grid1.Rows = 2 End Sub
490
Chapter 11
Step-2:
Note that to modify the properties of the DataGrid, right click on the DataGrid and select properties. Save the form as "frmWorks". Type the code as shown below: Option Explicit Dim db As Connection Dim rstWorks As Recordset Dim rstEmployee As Recordset Dim rstProject As Recordset Dim rstTemp As Recordset Private Sub cmdCancel_Click() Unload Me End Sub
Step-3:
491
492
txtHours.Text = "" rstWorks.AddNew End Sub Private Sub cmdSave_Click() On Error GoTo err1 rstWorks!ESSN = cboESSN.Text rstWorks!PNo = cboPNo.Text rstWorks!Hours = txtHours.Text rstWorks.Update Call Reset cboESSN.Enabled = False cboPNo.Enabled = False txtHours.Enabled = False cmdSave.Enabled = False cmdNew.Enabled = True Exit Sub err1: MsgBox Err.Description End Sub Private Sub Form_Load() Set db = New adodb.Connection db.Open "DSN=EMPL;UID=SCOTT;PASSWORD=TIGER;"
Chapter 11
Set rstWorks = New Recordset rstWorks.CursorLocation = adUseClient rstWorks.Open "Select * from Works_On", db, adOpenDynamic, adLockOptimistic Set rstEmployee = New Recordset rstEmployee.CursorLocation = adUseClient rstEmployee.Open "Select * from Employee", db, adOpenStatic, adLockReadOnly Set rstProject = New Recordset rstProject.CursorLocation = adUseClient rstProject.Open "Select * from Project", db, adOpenStatic, adLockReadOnly 'populate the ESSN combo box While Not rstEmployee.EOF cboESSN.AddItem (rstEmployee!SSN) rstEmployee.MoveNext Wend 'populate the PNo combo box While Not rstProject.EOF cboPNo.AddItem (rstProject!PNumber) rstProject.MoveNext Wend cboESSN.Enabled = False cboPNo.Enabled = False txtHours.Enabled = False cmdSave.Enabled = False Call Reset End Sub Private Sub Reset() Set rstTemp = New Recordset
493
rstTemp.CursorLocation = adUseClient rstTemp.Open "Select * from Works_on order by ESSN", db, adOpenStatic, adLockReadOnly Set DataGrid1.DataSource = rstTemp DataGrid1.Refresh End Sub
Step-3: Step-4:
Private Sub Form_Load() txtHelp.Text = "1. First enter all the divisions: " + Chr(13) + Chr(10) + "Department, Employee, Dependents, Project, etc. You must follow the same order." + Chr(13) + Chr(10) + Chr(13) + Chr(10) + _ "2. The Reports menu generates various reports like Employee details, Department details, etc." + Chr(13) + Chr(10) + Chr(13) + Chr(10) + _
494
Chapter 11
"3. You can search for an employee by giving SSN or Name." + Chr(13) + Chr(10) + Chr(13) + Chr(10) + _ "4. If you want to login as a different user, select File menu and click Login." End Sub Private Sub OKButton_Click() Unload Me End Sub Step-5: To design the "About" form, go to Project > Add Form and then select "About Dialog". Step-6: Step-7: Save the form as "frmAbout". You don't need to type any code for this form as VB automatically puts the code for you. However, to customize for our application, modify the Form_Load section only as shown below: Private Sub Form_Load() Me.Caption = "About Company Database" lblVersion.Caption = "Version " & App.Major & "." & App.Minor & "." & App.Revision End Sub The form is shown in Figure 11.29.
This completes the design of main forms. The next section would describe the details of Report generation.
495
Step-2:
Step-3:
496
Chapter 11
497
Step-6:
498
Chapter 11
Step-8:
499
This completes the entire design of the Company Database. You can now test the application by entering sample data and generate few reports. To receive the soft copy, please send an e-mail to the author (nand_gopalan@vsnl.net).
11.6ADDITIONAL EXAMPLES
This section discusses some more database problems and their solutions using SQL statements. A number of exercise problems for designing VB forms and reports are given at the end of this chapter. Readers are encouraged to solve these problems to get better understanding of the application development.
500
PARTICIPATED (Driverid# : String, RegNo : String, ReportNo : Int, DamageAmount : Int)
Chapter 11
(a) Create the above tables by specifying the primary keys and foreign keys. (b) Enter at least five tuples for each relation. (c) Demonstrate how you i) update the damage amount for the car with a specific RegNo in the accident with ReportNo 12 to 25000. (d) Find the total number of people who owned cars that were involved in accidents in 2002. (e) Find the number of accidents in which cars belonging to a specific model were involved. Solution (a) create table Person( Driverid# varchar2(5), Name varchar2(15) not Null, Address varchar2(20), primary key (Driverid#)); create table Car( RegNo varchar2(9), Model varchar2(15) not Null, Year integer not Null, primary key (RegNo)); create table Accident( ReportNo Integer, AccDate Date not Null, Location varchar2(15) not Null, primary key (ReportNo)); create table Owns( Driverid# varchar2(5), RegNo varchar2(9), primary key (Driverid#, RegNo), foreign key (Driverid#) references Person(Driverid#), foreign key (RegNo) references Car(RegNo)); create table Participated( Driverid# varchar2(5), RegNo varchar2(9),ReportNo Integer, DamageAmount integer, primary key (Driverid#, RegNo, ReportNo), foreign key (Driverid#) references Person(Driverid#), foreign key (RegNo) references Car(RegNo), foreign key (ReportNo) references Accident(ReportNo)); (b) Insert into Person values('1111', 'Ramu', 'K. S. Layout'); Insert into Person values('2222', 'Michel', 'Indiranagar'); Insert into Person values('3333', 'Priya', 'Rajajinagar'); Insert into Person values('4444', 'Gopal', 'Whitefield'); Insert into Person values('5555', 'Latha', 'Indiranagar'); Insert into Car values('KA04Q2301', 'MARUTHI-DX', 2000); Insert into Car values('KA05P1000', 'FORD IKON', 2002); Insert into Car values('KA03L1234', 'ZEN-VXI', 1999); Insert into Car values('KA03L9999', 'MARUTHI-STD', 2000); Insert into Car values('KA01P4028', 'INDICA-VX', 2004); Insert into Accident values(12, '01-JUN-2002', 'M G ROAD'); Insert into Accident values(200, '10-DEC-2002', 'DOUBLE ROAD'); Insert into Accident values(300, '23-JUL-1999', 'M G ROAD'); Insert into Accident values(25000, '11-JAN-2000', 'RESIDENCY ROAD'); Insert into Accident values(26500, '16-OCT-2001', 'RICHMOND ROAD');
501
Insert into Owns values('1111', 'KA04Q2301'); Insert into Owns values('1111', 'KA05P1000'); Insert into Owns values('2222', 'KA03L1234'); Insert into Owns values('3333', 'KA03L9999'); Insert into Owns values('4444', 'KA01P4028'); Insert into Participated values('1111', 'KA04Q2301', 12, 20000); Insert into Participated values('2222', 'KA03L1234', 200, 500); Insert into Participated values('3333', 'KA03L9999', 300, 10000); Insert into Participated values('4444', 'KA01P4028', 25000, 2375); Insert into Participated values('1111', 'KA05P1000', 26500, 70000); (c) update Participated set damageamount = 1111 where RegNo = 'KA01P4028' and ReportNo between 12 and 25000; insert into Accident values (31000, '3-Jan-2004', 'Wilson Garden'); insert into Participated values ('3333','KA03L9999', 31000, 5400); (d) SELECT COUNT(*) FROM ACCIDENT WHERE ACCDATE LIKE '__-___-02'; (e) Select count(*) from Car C, Participated P where C.RegNo = P.RegNo and Model = 'MARUTHI-DX';
502
Solution (a) Create table Customer( Cust# integer, CName varchar2(15) not Null, City varchar2(15), primary key (Cust#)); Create table CustOrder( Order# integer, ODate date not Null, Cust# integer, OrdAmt integer not Null, primary key (Order#), foreign key (Cust#) references Customer(Cust#)); Create table Item( Item# integer, Unitprice integer not Null, primary key (Item#)); Create table Order_Item( Order# integer, Item# integer, Qty integer, primary key (Order#, Item#), foreign key (Order#) references CustOrder(Order#), foreign key (Item#) references Item(Item#)); Create table Warehouse( Warehouse# integer, City varchar2(15) not Null, primary key (Warehouse#)); Create table Shipment( Order# integer, Warehouse# integer, Shipdate date, primary key (Order#, Warehouse#), foreign key (Order#) references CustOrder(Order#), foreign key (Warehouse#) references Warehouse(Warehouse#)); (b) Insert into Customer values (1111, 'Gupta', 'Bangalore'); Insert into Customer values (2222, 'Deepali', 'Mangalore'); Insert into Customer values (3333, 'Kiran', 'Chennai'); Insert into Customer values (4444, 'John', 'Bangalore'); Insert into Customer values (5555, 'Abbas', 'Belgaum'); Insert into CustOrder values (100, '01-JUN-2004', 1111, 10000); Insert into CustOrder values (200, '11-JUL-2004', 2222, 20000); Insert into CustOrder values (300, '21-DEC-2003', 3333, 30000); Insert into CustOrder values (400, '17-JUN-2004', 4444, 40000); Insert into CustOrder values (500, '11-JUL-2004', 2222, 50000); Insert into Item values (10, 500); Insert into Item values (20, 250); Insert into Item values (30, 100); Insert into Item values (40, 5); Insert into Item values (50, 5); Insert into Order_Item values (100, 10, 3); Insert into Order_Item values (200, 20, 10); Insert into Order_Item values (300, 10, 7); Insert into Order_Item values (400, 30, 3); Insert into Order_Item values (500, 40, 20);
Chapter 11
503
Insert into Warehouse values (1, 'Coimbatore'); Insert into Warehouse values (2, 'Pune'); Insert into Warehouse values (3, 'Cochin'); Insert into Warehouse values (4, 'Bangalore'); Insert into Warehouse values (5, 'Bangalore'); Insert into Shipment values (100, 1, '02-JAN-2002'); Insert into Shipment values (200, 2, '02-JAN-2002'); Insert into Shipment values (300, 3, '12-DEC-2001'); Insert into Shipment values (400, 4, '30-MAR-2004'); Insert into Shipment values (500, 4, '09-AUG-2000'); insert into shipment values(100, 5, '09-APR-2002'); (c) Select C.CName, count(CO.Order#), Avg(CO.OrdAmt) from Customer C, CustOrder CO where C.Cust# = CO.Cust# group by C.CName, CO.Cust#; (d) Select Order#, Warehouse# from Shipment where warehouse# in (select warehouse# from warehouse where City = 'Bangalore'); (e) Delete from Item where Item# = 10 and (update Order_Item set Item# = Null where Item# = 10);
504
create table Course( Course# integer, CName varchar2(15) not null, Dept varchar2(10) not null, primary key(Course#)); create table Enroll( RegNo varchar2(10), Course# integer, Sem integer not null, Marks integer, primary key(RegNo, Course#), foreign key (RegNo) references Student(RegNo), foreign key (Course#) references Course(Course#)); create table Text( ISBN integer, BookTitle varchar2(20) not null, Publisher varchar2(20), Author varchar2(15), primary key(ISBN)); create table Book_Adoption( Course# integer, Sem integer, ISBN integer, primary key(Course#, Sem), foreign key (Course#) references Course(Course#), foreign key (ISBN) references Text(ISBN)); (b) Insert into Student values('1BI00CS010', 'KIRAN', 'CSE', '02-JAN-1983'); Insert into Student values('1BI01ME075', 'DIVYA', 'MECH', '10-DEC-1984'); Insert into Student values('1BI02EC041', 'DIWAKAR', 'ELNS', '22-FEB-1984'); Insert into Student values('1BI00CS035', 'JOHN', 'CSE', '23-MAR-1982'); Insert into Student values('1BI03CS010', 'MUKUND', 'CSE', '15-AUG-1983'); Insert into Course values(11, 'DSC', 'CSE'); Insert into Course values(22, 'ADA', 'CSE'); Insert into Course values(33, 'CN', 'EC'); Insert into Course values(44, 'TD', 'MECH'); Insert into Course values(55, 'MuP', 'EC'); Insert into Enroll values('1BI00CS010', 22, 5, 72); Insert into Enroll values('1BI00CS010', 11, 3, 90); Insert into Enroll values('1BI02EC041', 33, 6, 52); Insert into Enroll values('1BI01ME075', 44, 4, 85); Insert into Enroll values('1BI00CS035', 22, 5, 75); Insert into Book_Adoption values(11, 3, 7722); Insert into Book_Adoption values(22, 4, 7722); Insert into Book_Adoption values(11, 5, 4400); Insert into Book_Adoption values(11, 8, 5566); Insert into Book_Adoption values(55, 4, 3388); Insert into Book_Adoption values(44, 4, 5566); Insert into Book_Adoption values(44, 7, 3388); Insert into Text values(7722, 'VB6', 'Dreamtech', 'Holzner'); Insert into Text values(1144, 'DS WITH C', 'Sapna', 'Nandagopal'); Insert into Text values(4400, 'C Programming', 'TMH', 'Balagurusamy'); Insert into Text values(5566, 'Computer NW', 'PHI', 'Tennenbaum'); Insert into Text values(3388, 'MuP', 'PHI', 'Brey');
Chapter 11
505
(c) Select C.Course#, T.ISBN, T.BookTitle from Course C,Book_Adoption BA, Text T where C.Course# = BA.Course# and BA.ISBN = T.ISBN and C.Dept = 'CSE' group by C.Course#, T.ISBN, T.BookTitle;
506
Foreign key (bookid) references catalog(Bookid)); (b) Insert into Author values(1000, 'Nandagopalan', 'Bangalore', 'India'); Insert into Author values(2000, 'Tony', 'Haywood', 'USA'); Insert into Author values(3000, 'Holzner', 'New York', 'USA'); Insert into Author values(4000, 'Tennenbaum', 'London', 'UK'); Insert into Author values(5000, 'Balaguruswamy', 'Chennai', 'India'); Insert into Publisher values(11, 'Wiely', 'New Delhi', 'India'); Insert into Publisher values(22, 'PHI', 'California', 'USA'); Insert into Publisher values(33, 'Sapna', 'Bangalore', 'India'); Insert into Publisher values(44, 'TMH', 'New York', 'USA'); Insert into Publisher values(55, 'Wrox', 'Texas', 'USA'); Insert into Category values(1, 'OS'); Insert into Category values(2, 'Languages'); Insert into Category values(3, 'Hardware'); Insert into Category values(4, 'Algorithms'); Insert into Category values(5, 'Internet'); Insert into Catalog values(123, 'DSC', 1000, 33, 2, 2000, 185); Insert into Catalog values(456, 'Networks', 4000, 44, 4, 2002, 365); Insert into Catalog values(789, 'VB6', 2000, 11, 2, 2000, 300); Insert into Catalog values(213, 'Frontpage2002', 4000, 44, 5, 2003, 500); Insert into Catalog values(879, 'ADA', 1000, 33, 4, 2001, 195); Insert into Order_Details values(112, 123, 100); Insert into Order_Details values(113, 123, 20); Insert into Order_Details values(114, 213, 50); Insert into Order_Details values(115, 789, 500); Insert into Order_Details values(116, 879,8); (c) select C.Authorid, A.AName from Catalog C, Author A where A.Authorid = C.Authorid and C.Year > 2000 and C.Price > (Select Avg(Price) from Catalog) group by C.Authorid, A.AName having count(C.Authorid) >= 2;
Chapter 11
(d) Create View SalesDetails as ( Select OD.Bookid as Book#, C.Price as Cost, Sum(OD.Quantity) as Qty, Sum(OD.Quantity * C.Price) as Sales from Order_Details OD, Catalog C, Author A where OD.Bookid = C.Bookid and C.Authorid = A.Authorid group by OD.Bookid, C.Price); select A.Authorid, A.AName,S.book#, S.Sales from Author A, catalog C, Salesdetails S where A.Authorid = C.Authorid and S.Book# = C.Bookid and sales = ( select Max(Sales) from salesdetails); (e) update Catalog set Price = Price * 1.10
507
The development process is same as what we have shown already in previous sections. Therefore, without explaining further the general menu structure may be designed as shown in Figure 11.37. In this application, the main menu items and sub menu items are arranged differently compared to the other applications. For example, from the main menu the users can navigate to open a Branch, or open a new Customer, or open a new Loan, etc. They can also enquire about Branches, or Accounts, or Balance amount of any account type. The Reports Menu is not filled with any specific details and is left to the reader to design relevant reports. Keeping these requirements, let us design the menu and is shown in Figure 11.38. Branch New Existing Delete Exit Customer New Existing Delete Account New Existing Delete Loan New Existing Delete Enquiry Branch Customer Account Loan Balance Reports Help Technical About
508
Chapter 11
Similarly, the other forms BranchNew, BranchExisiting, and BranchDel are shown in Figures 11.39 to 11.41.
509
Now, the VB codes for all the above forms appear in the next page:
510
Chapter 11
511
End If End Sub Private Sub Form_Load() 'On Error Resume Next 'Create connection object (for Oracle database) Set DB = New Connection DB.Open "DSN=Elective;UID=Prob5;PASSWORD=Prob5" 'Create recordset object Set rstBranch = New Recordset rstBranch.Open "Select * from Branch", DB, adOpenDynamic, adLockOptimistic 'Bind the form controls to database fields Set txtBrName.DataSource = rstBranch txtBrName.DataField = "BranchName" Set txtAssets.DataSource = rstBranch txtAssets.DataField = "Assets" 'Poplate branch city cboBrCity.AddItem "Mysore" cboBrCity.AddItem "Bangalore" cboBrCity.AddItem "Belgaum" cboBrCity.AddItem "Gulbarga" rstBranch.AddNew End Sub Private Sub txtAssets_Validate(Cancel As Boolean) If Not IsNumeric(txtAssets.Text) Then MsgBox "Please Enter Numbers in the Assets field", vbCritical, "Error in Data" txtAssets.SetFocus End If End Sub
512
Chapter 11
This application has been tested with some sample data and found working at all conditions.
513
learn how to specify the DSN, ODBC driver and record set statements in a Java program. Notice that most of the task is almost similar to VB6.0. The steps to build this databse example are very simple. The first step is to create a table named as Customer in Oracle9i with columns <CustID, CustName, Balance>. Next, specifiy CustID as primary key. The second step is to add few records and commit. Ensure that the ODBSC DSN for Oracle exists with the name Elective. This example uses JBuilder2005 to create the Java program. Create a java project named as customerdb and name the java program as Customer.java. For the complete program and output, see the below program:
package customerdb; /** * <p> JDBC - ODBC Demo (uses JBuilder 2005) * </p> * <p>Demo of how to connect to MS-Access Database from Java * it also shows how to retrieve the data from a table and display it * on the console * </p> * <p>Copyright: Copyright (c) 2005</p> * <p>Company: BIT </p> * @author S. Nandagopalan * @version 1.0 */ import java.sql.*; import sun.jdbc.odbc.*; class Customer { public Customer() { }
514
public static void main(String[] args) { try { // Connect to the Database with DSN: 'Elective' new JdbcOdbcDriver(); /* For MS-Access String url = "jdbc:odbc:Elective"; // jdbc: <subprotocol> : <subname> String user = ""; String password = ""; Connection con = DriverManager.getConnection(url, user, password); Statement stmt = con.createStatement(); } */ // For Oracle 9i String url = "jdbc:odbc:Elective"; // jdbc: <subprotocol>: <subname> String user = "scott"; String password = "tiger"; Connection con = DriverManager.getConnection(url, user, password); Statement stmt = con.createStatement(); System.out.println("Succsfully connected to Customer Database"); // Insert a new row in the Customer Table // stmt.executeUpdate("INSERT into Customer VALUES //('1000','NEWC ','J C Road ',8967.25)"); // Retrieve the data from 'Customer' table System.out.println("The Customer Data:"); ResultSet rs = stmt.executeQuery("Select * from Customer"); double total = 0; String cid; String cname; double cbal; while (rs.next()) { cid = rs.getString(1); cname = rs.getString(2); cbal = rs.getDouble("Balance"); // column name is Balance System.out.println(cid + "\t" + cname + "\t" + cbal); total += cbal; } System.out.println("Total Balance = " + total); rs.close(); } catch (Exception e) { e.printStackTrace(); } } }
Chapter 11
To use MS-Acces as back-end, simply remove the commented lines and comment the Oracle9i connection statements. The program computes the sum of the Balance column of all customers as shown in the next page.
515
Succsfully connected to Customer Database The Customer Data: 111 SNG 4500.0 222 Scott 9000.0 333 Allen 5600.0 Total Balance = 19100.0
Notice that cid, cname, and cbal are the host variables and assuming the table Customer has only three records.
11.7 SUMMARY
This Chapter discussed several important points with regard to the database application development Simple tutorials were given to get the basic idea of developing VB6.0 based applications. These tutorials used Oracle9i as the database where small tables were created Next, using the same front-end tool of VB6.0 it was shown how to make use of tables created using MS-Access Part-IV gave a very detailed and enterprise level database application development called Company database. Readers can apply this example for developing more sophisticated applications Finally, a number of examples were shown to develop SQL queries.
11.8 EXERCISES
11.1 Design and develop a complete database application using Oracle9i and VB6.0 for the following problems: a) b) c) d) e) f) g) Hospital Management System (in-patient and out-patient) Library Management (reference section, lending section, and journals) Cricket Database Management CD/DVD Library Management On-Line Examination System Inventory Control and Maanagement Car Sales and Service Management
All the above database applications require images to be maintained. Suggest the best and efficient way to store and retrieve images to and from the database. 11.2 Identify some meaningful reports and implement them using VB's Data Environment Report facility for the problems in 11.1.
516
Chapter 11
11.3
Develop suitable front-end for all the four additional problems dicussed in Section 11.6. Also design some useful reports for the databases. It is required to develop a database application for maintaining the student database for a college. Design a complete application using Java2 and Oracle9i.
11.4