Sunteți pe pagina 1din 92

Chapter 11

Application
Development-Tutorials

11.1 Tutorials using Oracle 9i & VB6.0………………..... 426


11.2 Tutorials using MS-Access & VB6.0.…………….... 448
11.3 Tutorials using MS-Sql & VB6.0…...……………..… 449
11.4 Compamy Database……………………..………….……. 453
11.5 Report Generation………………...…………………….… 495
11.6 Additional Examples……………………………….………. 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.
Application Development: Tutorials 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: Windows XP Professional


Database: Oracle 9i
Front-End Tool: VB 6.0

Step-1: Go to the SQL window. Click on Start > All programs > Oracle-OraHome90
> Application Development > SQL Plus.

Step-2: Type the following code in the SQL prompt:


CREATE TABLE Test (
RegNo VARCHAR2(10),
Name VARCHAR2 (20) NOT NULL,
PRIMARY KEY(RegNo));

Step-3: Click Start > Control Panel > Administrative tools > Data Sources(ODBC).

Step-4: 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”.

Step-6: Change Name property of the form to “Demo1” and the caption property to “Demo1”.

Step-7: Draw the following controls and assign the names as given below:

Name Type Caption

Label1 label RegNo


Label2 label2 Name
txtRegNo Text box
txtName Text box
cmdFirst Command Button <<

Name Type Caption


Application Development: Tutorials 429

cmdPrev Command Button <


cmdNext Command Button >
cmdLast Command Button >>
cmdSave Command Button &Save
cmdCancel Command Button &Cancel
cmdDelete Command Button &Delete
cmdExit 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.

Fig. 11.1 Layout of form Demo1


430 Chapter 11

Fig. 11.2 Setting of ActiveX Data Object Library

Step-9: Enter the code for the form load, and other controls as given in the next page.

Global Section
Option Explicit
Dim DB As Connection
Dim rstStudent As Recordset

Cancel Button
Private Sub cmdCancel_Click()
rstStudent.CancelUpdate
rstStudent.Requery
End Sub

Delete Button
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
rstStudent.Delete
rstStudent.MoveNext
If rstStudent.EOF Then
Application Development: Tutorials 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 Chapter 11

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


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
Application Development: Tutorials 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.

Fig. 11.3 Setting name to a Project

Exercise
Create a new table called “Projects” with attributes ”PNo”, “PName”, and “RegNo”. Here RegNo
is a foreign key, which references “RegNo” of “Student” table. Design a list box and a combo box.
The combo box should be populated with student register numbers (or name). When a register
number or name is selected from the combo box, the list box must be populated with all the
projects the student is working on.
The next tutorial solvs this exercise and is named as Tutorial-II.

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 Chapter 11

Step-2: Create a combo box and name it as “Combo1”.

Step-3: Create a list box and name it as “List1”.

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.

Fig. 11.4 Menu Editor

Step-5: Creating a tool bar is little tricky. Click Add-ins > Add-in Manager… > Application
Wizard and then check the Loaded/Unloaded and Load on Startup boxes (see Figure
(11.5). This step brings two items for the Add-ins called “Application Wizard” and
“Toolbar Wizard”.
Application Development: Tutorials 435

Fig. 11.5 Getting the Toolbar Wizard

Step-6: Click on Add-Ins > Toolbar Wizard… and add the appropriate icons as shown in Figure
11.6.

Fig. 11.6 Toolbar Wizard after the icons are selected


Step-7: After these steps, the form will look like as shown in Figure 11.7.
436 Chapter 11

Fig. 11.7 Final Form

Step-8: Type the code for various controls as follows: (Recall that to add the code for each
button/menu item/toolbar icon, simply double click or single click on the appropriate
control)

Option Explicit
Dim DB As Connection
Dim rstStudent As Recordset
Dim rstProject As Recordset

Private Sub mnuCancel_Click()


rstStudent.CancelUpdate
rstStudent.Requery
cmdSave.Enabled = False
mnuSave.Enabled = False
Toolbar1.Buttons.Item(2).Enabled = False
End Sub

Private Sub mnuDelete_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
rstStudent.Delete
Combo1.RemoveItem (rstStudent!Name)
rstStudent.MoveNext
If rstStudent.EOF Then
Application Development: Tutorials 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
Application Development: Tutorials 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 Chapter 11

End Sub

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
Application Development: Tutorials 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.

11.1.3 Tutorial - III


The primary purpose of this Tutorial-III is to develop an Enterprise Manager
Console (EMC) to maintain user accounts and the passwords. This console will
help the administrator to create, modify, and delete users. The passwords are
encrypted and stored in the database.

Another advantage of this application is that any database application can use
this package for security purposes. The steps needed to develop this application
are shown in the following steps. Since we have already shown detailed steps in
creating form(s), menus, and tool bar, this tutorial does not give the steps in detail.

Step-1: Create a table called “Users” in the SQL prompt as follows:


CREATE TABLE Users (
id VARCHAR2(10),
passwd VARCHAR2(10) NOT NULL,
PRIMARY KEY(id));

Step-2: Create a new form and give the “frmEMC” and its caption property as “Enterprise
Manager Console”. Save the project by giving the name as “Security”.

Step-3: The form should have the following controls:


442 Chapter 11

Control Type Property Name Caption

Frame Frame1 New User


Label User Name -
Label Password -
Label Confirm Password -
Text box txtUsrName -
Text box txtPass -
Text box txtConform -
Command button cmdCancel &Cancel
Command button cmdSave &Save
Frame Frame2 Existing Users
DataGrid DataGrid1 Password Table
Command button cmdShow S&how users
Command button cmdConnect Connec&t
Frame Frame3 Privileges
Check box CheckM -
Check box CheckD -
Label Label3 Allow Modify
Label Label4 Allow Delete
ADODC Adodc1 Adodc1
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.

File Edit Help

New user… Ctrl+N Change Password… Contents

Save user Ctrl+S Modify User… About

Exit Ctrl+X Delete User… Ctrl+D

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).

Step-6: 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
Application Development: Tutorials 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 Chapter 11

Private Sub mnuchange_Click()


MsgBox "Left as Exercise", vbInformation
End Sub

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
Application Development: Tutorials 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

Fig. 11.8 Security form

Private Sub txtUsrName_Validate(Cancel As Boolean)


If Len(txtUsrName.Text) < 3 Or Len(txtUsrName.Text) > 10 Then
MsgBox "Username should be minimum 3 characters and not more than 10
characters", vbExclamation, "Error"
txtUsrName.SetFocus
SendKeys "{Home}+{End}"
Cancel = True
End If
End Sub

Step-7: Create a second form with name “frmLogin” and caption “Login”. Save the form as
“frmLogin” (See Figure 11.9).
Application Development: Tutorials 447

Fig. 11.9 Login Form

Step-8: Type the code for this as shown below:

Dim DB As Connection
Dim rstId As Recordset
Public LoginSucceeded As Integer

Private Sub cmdCancel_Click()


'set the global var to false
'to denote a failed login
LoginSucceeded = False
Unload Me
End Sub

Private Sub cmdOK_Click()


If txtUserName = "manager" And txtPassword = "bit" Then
LoginSucceeded = 1 'Administrator
txtUserName.Text = ""
txtPassword.Text = ""
Me.Hide
frmEMC.Show vbModal
ElseIf RecStatus = True Then
LoginSucceeded = 2 'Ordinary users
MsgBox "Other Users"
txtUserName.Text = ""
txtPassword.Text = ""
Me.Hide
Else
MsgBox "Invalid Password, try again!", , "Login"
txtUserName.SetFocus
SendKeys "{Home}+{End}"
End If
End Sub

Private Function RecStatus() As Boolean


Dim strUsername As String
Dim strPasswd As String
Dim strSQL As String
strUsername = txtUserName.Text
strPasswd = txtPassword.Text
strPasswd = Encrypt_password
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()
Application Development: Tutorials 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\Tutorial-
I\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 MS-
Acces 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

Fig. 11.10 "Product" Table structure

Step-1: Create a DSN called "T1" for SQL Server. The procedure is same as that of the
example shown in Section 11.4.4. However, you must select an appropriate "Data
Source" i.e. SQL Server) from the window "Create New Data Source".

Step-2: Create a table called "Product" in SQL Server (see figure 11.10).

Step-3: The next task is to create a form in VB with various controls as shown in Figure 11.11.

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
Application Development: Tutorials 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
Application Development: Tutorials 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.

11.4.1 Conceptual Design


This section talks about the conceptual design aspects for the problem described in
Section 11.4. Recall that Section 3.2 explained the conceptual design of this problem
and Figure 3.13 depicted the ER diagram for the same.

In addition, Figure 4.2 showed the table structure for the entire application
after normalization. Remember, to solve any new problem, you are expected to
start with an ER diagram, translate into tables, and normalize these tables at least
up to BCNF level. In our example, all these steps have already been done and so
we can proceed to create these tables in Oracle9i. The next section does this.

11.4.2 Creating Tables in Oracle9i


The first step in the implementation process is to create all tables using Oracle SQL.
This section explains the steps required to achieve this goal.

Step-1: In the SQL prompt, type the following programs: (alternatively, you can enter these
programs in a notepad and copy and paste in the SQL prompt).
Application Development: Tutorials 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 Chapter 11

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;

11.4.3 Front-End Design Requirements


We must now decide the design of several forms for populating the tables. This
section describes the steps to design various menus, forms, and navigation details.
Following requirements must be met:

1. To provide access privileges in using the application, we shall provide two


users: (1) a super user called as "ceo" with password "apple" (2) an ordinary
clerk "clerk" with password "lion". The user "ceo" holds all the privileges
(add, delete, and modify), whereas the user clerk can not delete any
records.
2. There should be a form to show the employee records with search options.
The user must be able to search based upon SSN/Name of the employee.
Also the records must be shown in a tabular form.
3. A set of forms for adding employee records, department records, project
records, work details, department locations, etc. must be designed. These
forms may be supported with browsing facility. Also facility to modify and
delete the records shall be provided.
4. A separate form for calculating the total wages for employees is to be made
as part of the project.
5. Finally, some meaningful and also useful reports using the VB's data
reports must be designed.
Application Development: Tutorials 457

11.4.4 Setting up Data Source Name (DSN)


The first thing you must do is to set up the ODBC connectivity to the Oracle
database (recall, you have done the same work in Tutorial-I). In order to do this
you must execute the following steps:

Step-1: Start > Control Panel. Double click on Administrative Tools and double click on Data
Sources (ODBC). You will see the screen similar to the one shown in Figure 11.12.

Fig. 11.12 DSN settings

Step-2: Press Add button to create a new DSN source. After pressing Add button, you should
see a screen as shown in Figure 11.13.

Step-3: Select Microsoft ODBC for Oracle and then click on Finish button. Then another
small window appears as shown in Figure 11.14.
458 Chapter 11

Fig. 11.13 Selecting a new Data Source

Fig. 11.14 Creating new (Data Source Name) DSN

Step-4: Enter "empl" in Data Source Name and then press OK. There is no need to enter
other details in this window.

With this step, you have successfully created a new data source name called
"empl" for Oracle ODBC.

11.4.5 Design of Login Form (frmLogin)


The main objective of a login form is to get the user name and password. If it
matches with the predefined values, the user will be allowed to use the database
Application Development: Tutorials 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.

Fig. 11.15 Login Form

Step-2: Double click on "OK" button and "Cancel" button and type the appropriate code as
shown below:

Option Explicit
Public LoginSucceeded As Integer

Private Sub cmdCancel_Click()


'set the global var to false
'to denote a failed login
LoginSucceeded = 0
Unload Me
End Sub

Private Sub cmdOK_Click()


'check for correct password
If txtUserName = "ceo" And txtPassword = "apple" Then
'login successfull for super user
LoginSucceeded = 1
Me.Hide
frmMainForm.Show
ElseIf txtUserName = "clerk" And txtPassword = "lion" Then
'login successfull for clerk
LoginSucceeded = 2
Me.Hide
frmMainForm.Show
Else
'login failed
LoginSucceeded = 0
MsgBox "Invalid User Name/Password, try again!", , "Login"
txtUserName.SetFocus
SendKeys "{Home}+{End}"
End If
460 Chapter 11

'clear the field


txtPassword.Text = ""
End Sub

11.4.6 Design of Main Form


In this section you will study about the methodology in creating the opening or
main form which contains the navigation details in the form of submenus. Figure
11.16 shows the complete menu.

File Divisions Reports Help

Login Ctrl+N Employee Details  Employees Employee Details Technical Support F2

Exit Ctrl+Q Department Details  Work Info Employee Wage Details About

Projects Department Details

Project Details

Fig. 11.16 The Main Menu Layout

Step-1: Create the above menu by invoking the menu editor and type the following details:

Caption Name Shortcut

&File DbAcc
&Login Dblogin Ctrl+N
E&xit DbExit Ctrl+Q

&Divisions mnucmp
&Employee Details mnuemp
E&mployees mnuepl Ctrl+M
&Work Info mnuwrks Ctrl+W
D&epartment Details mnuDep
Departments… mnuDept Ctrl+E
Department &Locations mnudeploc Ctrl+L
&Projects mnuProj

&Reports mnurep
Employee Details mnuREmp
Employee Wage Details mnuRDept
Project Details mnuRProject

&Help AppHelp
&Technical Support Appulse F2
About ApplAbout
Application Development: Tutorials 461

Figure 11.17 shows the "frmMainForm" and its Picture property is set with the
bitmap image.

Fig. 11.17 The Main Form

Step-2: Type the following code by double clicking the appropriate menu item.

Dim db As Connection
Private Sub ApplAbout_Click()
frmAbout.Show vbModal
End Sub

Private Sub Appluse_Click()


frmTechnical.Show
End Sub

Private Sub DbExit_Click()


End
End Sub

Private Sub DbLogin_Click()


frmLogin.Show vbModal
End Sub

Private Sub imgEmp_Click()


462 Chapter 11

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!

11.4.7 Design of Employee Form


The design of Employee form is same as other forms that have been created
already. In fact, this form enables the users to maintain all the employee data. You
Application Development: Tutorials 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

Fig. 11.18 Employee form


Step-2: The controls that you see in the Figure are DataGrid1, a command button (Show
Dependents), a command button (Close), a tool bar, and menu items. The names of
the menu items can be taken from the code that is given next.

Step-3: Save the form as "frmEmployee".


Step-4: Type the code as listed below:

Option Explicit
Dim db As Connection
Dim rstEmployee As Recordset
Dim rstEmpFind As Recordset
Public strSSN As String 'to acces in frmModifyEmp form

Private Sub cmdClose_Click()


Unload Me
End Sub

Private Sub cmdShow_Click()


Dim choice As String
If DataEnvironment1.rscmdDependents.State = adStateOpen Then
DataEnvironment1.rscmdDependents.Close
End If

choice = DataGrid1.Columns(1)
DataEnvironment1.cmdDependents choice
464 Chapter 11

Load rptDependent
rptDependent.Show vbModal
End Sub

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
Application Development: Tutorials 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 Chapter 11

End Sub

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

11.4.8 Design of AddEmployee Form & Dependents Form


To make the Employee form work successfully, we need two more form, i.e. to add
new employees to the database and add dependents details for the employees. Let
us create two forms to accomplish this task.

Step-1: Create a new form and name it as "frmAddEmployee" and save it with the name.

Step-2: Add the following controls as given below:

Control Type Name Property Caption Property

Text Box txtSSN -


Text Box txtName -
Combo Box cboDay -
Combo Box cboMonth -
Combo Box cboYear -
Text Box txtAddr -
Combo Box cboSex -
Text Box txtSalary -
Combo Box cboSSSN
Combo Box cboDNo -
Command Button cmdAdd Add
Command button cmdCancel Cancel
Application Development: Tutorials 467

The Figure 11.19 shows the form with these controls and the labels.

Fig. 11.19 frmAddEmployee Form

Step-3: Type the code as shown below:

Option Explicit
Dim db As Connection
Dim rstEmployee As Recordset
Dim rstDept As Recordset
Dim rstSuperSSN As Recordset
Private Sub cmdAdd_Click()
On Error GoTo err1
Dim strDate As String
Dim UsrDate As Date
Dim CurrentDate As Date
strDate = cboDay.Text + "/" + cboMonth.Text + "/" + cboYear.Text
UsrDate = Format(strDate, "dd/mmm/yyyy") 'convert string to date
CurrentDate = Format(Now, "dd/mmm/yyyy") 'convert string to date
If Not UsrDate > CurrentDate Then
rstEmployee!SSN = txtSSN.Text
rstEmployee!Name = txtName.Text
rstEmployee!BDate = strDate
rstEmployee!Address = txtAddr.Text
rstEmployee!Sex = cboSex.Text
rstEmployee!Salary = Val(txtSalary.Text)
rstEmployee!SuperSSN = cboSSSN.Text
rstEmployee!DNo = Val(cboDNo.Text)
rstEmployee.Update
Unload Me
Else
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
Application Development: Tutorials 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.

Step-5: 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
Application Development: Tutorials 471

cboSSN
cmdAdd
txtName

txtBDate

cboSex

cboRelation cmdCancel

Image1
cboEmpSSN

DataGrid
1
cmdDelete

cmdClose

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 Chapter 11

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

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


Application Development: Tutorials 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.

Fig. 11.21 frmModifyEmp form – to modify employee details

Step-7: Type the code as given below:

Option Explicit
Dim db As Connection
Dim rstEmployee As Recordset
Dim rstDate As Recordset
Dim rstDept As Recordset
Dim rstSuperSSN As Recordset
Application Development: Tutorials 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 Chapter 11

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"
Application Development: Tutorials 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

11.4.9 Design of Department Form


The next task for our Company Database is to design the Department Form. This
time we shall present the form layout in a slightly different way. It contains just a
tool bar with five icons for Stop, New, Save, Cancel, and Delete the department
records.

txtDNo cmdCanc
el
txtDName

cboMSSN

txtMDate
cmdClose

cmdFirst cmdPrev cmdNext cmdLast

Fig. 11.22 Department Form


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".

Step-2: Right lick on the ImageList1 and select properties and select the Images tab (see
Figure 11.23).

Fig. 11.23 Designing the tool bar

Step-3: By clicking the "Insert Picure" button you can add any image (.ico, or .jpg, or .bmp
files). For each button, an index value is attached. This index value can be used to
reference appropriate image at the time coding. The figure shows after adding the
required five buttons for application.

Step-4: From the toolbox, select "Toolbar", and draw it on the form. The tool bar will look
empty. Right click on the tool bar and select properties. From the "General" tab, set the
ImageList combo box to "ImageList1". Then, click on the "Buttons" tab. To add a
toolbar icon, click "Insert Button" button and enter 1 in the "Image" text box (refers to
the first image of the ImageList1). Similarly you can add more icons, but ensure that
you fill up the Image text box with the corresponding image index (see Figure 11.24).
Application Development: Tutorials 479

Fig. 11.24 Adding toolbar icons

You can type relevant text in the "Tooltip Text" box.

Step-5: Type the code as shown below:

Option Explicit
Dim db As Connection
Dim rstEmployee As Recordset
Dim rstDept As Recordset

Private Sub cmdCancel_Click()


On Error Resume Next
cboDay.Visible = False
cboMonth.Visible = False
cboYear.Visible = False
txtMDate.Visible = True
cmdFirst.Enabled = True
cmdPrev.Enabled = True
cmdNext.Enabled = True
cmdLast.Enabled = True
rstDept.CancelUpdate
rstDept.CancelUpdate
End Sub
Private Sub cmdFirst_Click()
480 Chapter 11

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

'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"
Application Development: Tutorials 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 Chapter 11

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

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
Application Development: Tutorials 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

11.4.10 Design of Project Form


The Project form can be designed exactly same as the previous form, except for
changes in the labels. Therefore, we will not give the details for this form but only
the code (see Figure 11.25).

Option Explicit
Dim db As Connection
Dim rstProject As Recordset
Dim rstDept As Recordset

Private Sub cmdCancel_Click()


cmdFirst.Enabled = True
cmdPrev.Enabled = True
cmdNext.Enabled = True
cmdLast.Enabled = True
Toolbar1.Buttons.Item(2).Enabled = True
Toolbar1.Buttons.Item(5).Enabled = True
rstProject.CancelUpdate
End Sub

Private Sub cmdFirst_Click()


On Error Resume Next
rstProject.MoveFirst
cmdPrev.Enabled = False
cmdNext.Enabled = True
End Sub

Private Sub cmdLast_Click()


On Error Resume Next
rstProject.MoveLast
cmdNext.Enabled = False
cmdPrev.Enabled = True
End Sub
484 Chapter 11

Private Sub cmdNext_Click()


On Error Resume Next
rstProject.MoveNext
If rstProject.EOF Then
rstProject.MoveLast
End If
cmdPrev.Enabled = True
End Sub

Fig. 11.25 Project Form (frmProject)

Private Sub cmdPrev_Click()


On Error Resume Next
rstProject.MovePrevious
If rstProject.BOF Then
rstProject.MoveFirst
End If
cmdNext.Enabled = True
Exit Sub
End Sub

Private Sub Form_Load()


Set db = New adodb.Connection
db.Open "DSN=EMPL;UID=SCOTT;PASSWORD=TIGER;"

Set rstProject = New Recordset


rstProject.CursorLocation = adUseClient
rstProject.Open "Select * from Project", db, adOpenDynamic, adLockOptimistic
Application Development: Tutorials 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

11.4.11 Design of Department Locations Form


We shall adopt a unique technique to design this form. The requirement for this
form is that we must get the department number and the locations. For each
department, we may have one or more locations. Instead of adding individual
Application Development: Tutorials 487

records, we shall use a FlexGrid to obtain all the records (maximum is say 3) and
save together in the database.

Step-1: Go to Project > Add Form > Form, then click Open.

Step-2: Draw the controls as indicated in the Figure 11.26.

Control Name Caption

Frame Frame1 Dept and Locations


Combo Box cboDeptNo -
Combo Box cboDeptLoc -
Command Button cmdAdd Add

Frame Frame2 Records


MSFlexGrid Grid1 -
Command Button cmdSave Save
Command Button cmdCancel Cancel

Fig. 11.26 frmDeptLoc Form


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
Application Development: Tutorials 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

11.4.12 Design of Employee Work Details


To populate the Works_On table, we need a form. Let us call this form as
"frmWorks". We select the SSN and the Project No from the combo boxes; then
enter the number of hours an employee worked on this project. When you save the
record, you automatically get the table updated; that is, shown in the DataGrid.
With these requirements in mind, the Works form will look like the one shown in
Figure 11.27.

Step-1: Add a new form and draw the controls.

Control Name Caption

Frame Frame1 Work Details


Combo Box cboESSN -
Combo Box cboPNo -
Command Button cmdNew New
Command Button cmdSave Save

Frame Frame2 Employee Work table


DataGrid DataGrid1 -
Command Button cmdDelete Delete
Command Button cmdCancel Cancel

Step-2: Note that to modify the properties of the DataGrid, right click on the DataGrid and
select properties. Save the form as "frmWorks".

Step-3: 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
Application Development: Tutorials 491

Fig. 11.27 Employee Work Form (frmWorks)

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 Works_On where ESSN = " & ChoiceSSN
db.Execute strSQL
Call Reset
DataGrid1.AllowDelete = False
End If
Exit Sub
err1:
MsgBox Err.Description
End Sub

Private Sub cmdNew_Click()


cmdNew.Enabled = False
cboESSN.Enabled = True
cboPNo.Enabled = True
txtHours.Enabled = True
cmdSave.Enabled = True
cboESSN.Text = ""
cboPNo.Text = ""
492 Chapter 11

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;"

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
Application Development: Tutorials 493

rstTemp.CursorLocation = adUseClient
rstTemp.Open "Select * from Works_on order by ESSN", db, adOpenStatic,
adLockReadOnly
Set DataGrid1.DataSource = rstTemp
DataGrid1.Refresh
End Sub

11.4.13 Design of Help Menu (Technical Form and About Form)


You might have noticed that there are two submenu items in the "Help" menu. The
first one is "Technical Support" and the second is "About". To design the first form,
we need just a multi-line text box and "OK" button. So it becomes very easy. Look
at the Figure 11.28.

Fig. 11.28 Help menu design (frmTechnical)

Step-1: Add a new form with name "frmTechnical" and save the form with the same name.

Step-2: Draw a text box with name "txtName" and set its Multiline property to "true". You will
see a scroll bar attached automatically at design time and also at run time.

Step-3: Draw a Command Button called "cmdOK" with its caption property set to "OK".

Step-4: Type the following code:

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: Save the form as "frmAbout".

Step-7: 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.

Fig. 11.29 Design of About form ("frmAbout")

This completes the design of main forms. The next section would describe the
details of Report generation.
Application Development: Tutorials 495

11.5 REPORT GENERATION


Without useful reports from the database, our application is incomplete. Hence, let
us explain the steps needed to design VB reports for the Company database. Let us
design few simple reports, but show the steps in detail. To design reports in VB do
the following steps:

Step-1: Go to Project > Add data Environment. You will see a default data environment by
name "Data Environment1" and a default connection "Connection1" (see Figure
11.30).

Step-2: Right click on "Connection1" and select "Add Command". By doing this you will get a
default command called "Command1". You can change the names of these controls by
going to the properties menu. For our application change the name of the command to
"cmdEmployee"

Step-3: Right click on the "cmdEmployee" and select the properties. You will see a new
window and check the SQL Statement. Type the SQL statement as shown in Figure
11.31 and click "OK" button.

Fig. 11.30 Creating Data Environment


496 Chapter 11

Fig. 11.31 Query statement for Employee report

Step-4: Similarly, create four more commands by right clicking the "Connection1". Give the
names as "cmdDependents", "cmdWages", "cmdProject", "cmdDept". Type the code
for each of these commands as shown below. See Figures 11.32.

Code for "cmdDependents":


Select * from Dependent where ESSN = ?

Code for "cmdWages":


Select SSN, Name, TotalHrs, TotalHrs * ? from Employee, SSNHrs where SSN =
ESSN

Code for "cmdProject"


Select PNumber, PName, PLocation, DName from Project, Department where
Project.DNum = DNumber

Code for "cmdDept":


Select D.DName, E.Name, D.MgrStartDate, DL.DLocation from Employee E,
Department D, Dept_Locations DL where E.SSN = D.MgrSSN and D.DNumber =
DL.DNumber order by D.DName
The ? indicates the parameter which will be sent when the command is invoked.
Application Development: Tutorials 497

Fig. 11.32 Creation of "Commands"

Step-5: The next step is to design the layout for the reports. Click on Project > Add Data
Report. You will see a default data report called "Datareport1" created. Rename it as
"rptEmployee".

Step-6: Change the name property to "Employee Details". Firstly, select the data report
window. Next, click on the Data Source property and select "Data Environment1".
Finally, select the Data Member property and select the appropriate command. In this
case, click on "cmdEmployee" (See Figure 11.33).
498 Chapter 11

Fig. 11.33 Designing Data Report

Step-7: Right Click on the Detail Section > Insert Control > Textbox. Select Data Member
property and select "cmdEmployee". Next, you must select Data member property and
click the appropriate field. Continue this process until you create textboxes for all the
fields. Create labels wherever required. Recall that the textboxes in the "Detail" section
will be filled by all the records of the table.

Step-8: Repeat Steps-5 to Step-7 for the remaining commands. The reports for Employee and
Department at run time are shown in Figure 11.34.
Application Development: Tutorials 499

Fig. 11.34 Employee Report

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.

11.6.1 Insurance Database


Consider the Insurance database given below. The primary keys are underlined
and the data types are specified.
PERSON (Driverid# : String, Name : String, Address : String)
CAR (RegNo : String, Model : String, Year : Int)
ACCIDENT (ReportNo : Int, AccDate : Date, Location : String)
OWNS (Driverid# : String, RegNo : String)
500 Chapter 11

PARTICIPATED (Driverid# : String, RegNo : String, ReportNo : Int,


DamageAmount : Int)
(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');
Application Development: Tutorials 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';

11.6.2 Order Processing Database


Consider the Order Processing database given below. The primary keys are
underlined and the data types are specified.
CUSTOMER (Cust# : Int, CName : String, City : String)
CUSTORDER (Order# : Int, ODate : Date, Cust# : Int, OrdAmt : Int)
ORDER_ITEM (Order# : Int, Item# : Int, Qty : Int)
SHIPMENT (Order# : Int, Warehouse# : Int, Shipdate : Date)
WAREHOUSE (Warehouse# : Int, City : String)
(a) Create the above tables by specifying the primary keys and foreign keys.
(b) Enter at least five tuples for each relation.
(c) Produce a listing: CustName, #ofOrders, Avg_Order_Amt, where the middle column is the
total number of orders made by the customer and the last column is the average order amount
for that customer.
(d) List the order# for orders that were shipped from all the warehouses that the company has in
a specific city.
(e) Demonstrate how you delete item# 10 from ITEM table and make that field null in the
ORDER_ITEM table.
502 Chapter 11

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);
Application Development: Tutorials 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);

11.6.3 Student Enrollment Database


Consider the Student Enrollment database given below. The primary keys are
underlined and the data types are specified.
STUDENT (RegNo : String, Name : String, Major : String, BDate : date)
COURSE (Course# : Int, CName : String, Dept : String)
ENROLL (RegNo : String, Course# : Int, Sem : Int, Marks : Int)
BOOK_ADOPTION (Course# : Int, Sem : Int, ISBN : Int)
TEXT (ISBN : Int, BookTitle : String, Publisher : String, Author : String)
(a) Create the above tables by specifying the primary keys and foreign keys.
(b) Enter at least five tuples for each relation.
(c) Produce a list of text books (include Course#, ISBN, BookTitle) in the alphabetical order for
courses offered by the 'CS' department that use more than two books.

Solution
(a)
create table Student(
RegNo varchar2(10), Name varchar2(20) not null,
Major varchar2(10) not null, BDate date,
primary key(RegNo));
504 Chapter 11

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');
Application Development: Tutorials 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;

11.6.4 Book Dealer Database


Consider the Book dealer database given below. The primary keys are underlined
and the data types too are specified.
AUTHOR (Authorid : Int, Name : String, City : String, Country : String)
PUBLISHER (Publisherid : Int, Name : String, City : String, Country : String)
CATALOG (Bookid : Int, Title : String, Authorid : Int, Publisherid : Int, Categoryid : Int, Year : Int,
Price : Int)
CATEGORY (Categorid : Int, Description : String)
ORDER_DETAILS (OrderNo : Int, Bookid : Int, Quantity : Int)
(a) Create the above tables by specifying the primary keys and foreign keys.
(b) Enter at least five tuples for each relation.
(c) Give the details of the authors who have 2 or more books in the catalog and the proce of the
books is greater than the average price of the books in the catalog and the year of publication is
after 2000.
(d) Find the number of the book which has maximum sales.
(e) Demonstrate how you increase the price of books published by a specific publisher by 10%.

Solution
(a)
Create table Author(
Authorid integer, AName varchar2(15), ACity varchar2(15), ACountry varchar2(15),
primary key (Authorid));
Create table Publisher(
Publisherid integer, PName varchar2(15), PCity varchar2(15), PCountry varchar2(15),
primary key (Publisherid));

Create table Category(


Categoryid integer, Description varchar2(20),
primary key(Categoryid));

Create table Catalog(


Bookid integer, Title varchar2(20), Authorid integer, Publisherid integer,
Categoryid integer, Year integer, Price integer,
primary key (Bookid),
Foreign key (Authorid) references Author(Authorid),
Foreign key (Publisherid) references Publisher(Publisherid),
Foreign key (Categoryid) references Category(Categoryid));

Create table Order_Details(


OrderNo integer, Bookid integer, Quantity integer,
primary key (OrderNo, Bookid),
506 Chapter 11

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;

(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
Application Development: Tutorials 507

where Publisherid = 33;

11.6.5 Bank Database


You will understand, in this section, an application that is developed using Oracle
9i and VB 6.0 to maintain bank accounts and loan details of customers. Fisrt of all,
assume that the following tables are given to us:
BRANCH (Branch_Name : String, Branch_City : String, Assets : Real)
ACCOUNT (AccNo : Integer, Branch_Name : String, Balance : Real)
DEPOSITOR (Customer_Name : String, AccNo : Integer)
CUSTOMER (Customer_Name : String, Customer_Street : String,
Customer _City : String)
LOAN (Loan_Number : Integer, Branch_Name : String, Amount : Real)

BORROWER (Customer_Name : String, Loan_Number : Integer)

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 Customer Account Loan Enquiry Reports Help


New New New New Branch Technical
Existing Existing Existing Existing Customer About
Delete Delete Delete Delete Account
Exit Loan
Balance

Fig. 11.37 Menu Structure of Bank Database


508 Chapter 11

Fig. 11.38 The Main Menu

Similarly, the other forms BranchNew, BranchExisiting, and BranchDel are


shown in Figures 11.39 to 11.41.

Fig. 11.39 BranchNew Form


Application Development: Tutorials 509

Fig. 11.40 BranchExisting Form

Fig. 11.41 BranchDel Form

Now, the VB codes for all the above forms appear in the next page:
510 Chapter 11

Code for Main Form


Private Sub mnuBrDelete_Click()
BranchDel.Show vbModal
End Sub

Private Sub mnuBrExisting_Click()


BranchExisting.Show
End Sub

Private Sub mnuBrNew_Click()


BranchNew.Show vbModal
End Sub

Private Sub mnuExit_Click()


End
End Sub

Code for BranchNew Form


Option Explicit
Dim DB As Connection
Dim rstBranch As Recordset

Private Sub cmdCancel_Click()


Unload Me
End Sub
Private Sub cmdSubmit_Click()
On Error GoTo Err
Dim intFlag As Integer
intFlag = 0
If txtBrName.Text = "" Then
MsgBox "Branch Name is empty"
intFlag = 1
End If
If cboBrCity.ListIndex = -1 Then
MsgBox "Branch City is empty"
intFlag = 1
End If
If txtAssets.Text = "" Then
MsgBox "Assets is empty"
intFlag = 1
End If
If intFlag = 0 Then
rstBranch!branchname = txtBrName.Text
rstBranch!branchcity = cboBrCity.Text
rstBranch!assets = txtAssets.Text
rstBranch.Update
MsgBox "Record saved successfully", vbInformation, "Save Status"
Unload Me
End If
Exit Sub
Err:
If Err.Number = -2147217873 Then 'Violation of primary key constraint
MsgBox "Duplicate Branch Name", vbCritical, "Error"
Application Development: Tutorials 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

Code for BranchExisting Form


Option Explicit
Dim DB As Connection
Dim rstBranch As Recordset

Private Sub cmdBack_Click()


Unload Me
End Sub

Private Sub Form_Load()


'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.CursorLocation = adUseClient
rstBranch.Open "Select * from Branch order by BranchName", DB, adOpenStatic,
adLockReadOnly
Set DataGrid1.DataSource = rstBranch
DataGrid1.Refresh
End Sub
512 Chapter 11

Code for BranchDel Form


Option Explicit
Dim DB As Connection
Dim rstBranch As Recordset

Private Sub cmdBack_Click()


Unload Me
End Sub

Private Sub cmdDelete_Click()


Dim ChoiceBranch As String
Dim intChoice As Integer
Dim strSQL As String
If cboDelete.ListIndex = -1 Then
MsgBox "You must select a Branch", vbExclamation
cboDelete.SetFocus
Exit Sub
End If
intChoice = MsgBox("Are sure you want to delete?", vbYesNo + vbCritical)
If intChoice = vbYes Then
ChoiceBranch = cboDelete.Text
strSQL = "Delete from Branch where BranchName = " & "'" & ChoiceBranch & "'"
DB.Execute strSQL
MsgBox "Branch Successfully Deleted", vbInformation, "Delete Status"
Unload Me
End If
End Sub

Private Sub Form_Load()


'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.CursorLocation = adUseClient
rstBranch.Open "Select * from Branch order by BranchName", DB, adOpenStatic,
adLockReadOnly
While Not rstBranch.EOF
cboDelete.AddItem (rstBranch!BranchName)
rstBranch.MoveNext
Wend
End Sub

This application has been tested with some sample data and found working at
all conditions.

11.6.6 Customer Database (Java2 and Oracle9i)


It is possible use Java2 as front-end tool for any DBMS. Let us show a simple
example by using Oracle9i as a back-end database. This tutorial should help you to
Application Development: Tutorials 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 Chapter 11

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();
}
}
}

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.
Application Development: Tutorials 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) Hospital Management System (in-patient and out-patient)
b) Library Management (reference section, lending section, and journals)
c) Cricket Database Management
d) CD/DVD Library Management
e) On-Line Examination System
f) Inventory Control and Maanagement
g) 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.

11.4 It is required to develop a database application for maintaining the student


database for a college. Design a complete application using Java2 and
Oracle9i.

Data Source Name (DSN), 457 ODBC driver, 513


Java2 and Oracle9i, 512 Report Generation, VB, 495

S-ar putea să vă placă și