Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
107 views31 pages

Database Connectivity: Data Access Objects (DAO)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 31

Object-Oriented Programming 3.

51

DATABASE CONNECTIVITY

Data Access Objects (DAO)


 DAO enables you to use a programming language to access and manipulate data in
local or remote databases and to manage databases, their objects, and their structure.
 DAO supports two different database environments, or "workspaces".
 Microsoft jet workspaces allow to access data in Microsoft jet databases, Microsoft jet
connected ODBC databases, and installable ISAM data sources in other formats, such
as Paradox of Lotus 1-2-3.
Object-Oriented Programming 3.51

Microsoft JET WORKSPACE


 WorkSpace is used to access the data source by using the Microsoft jet database
engine. The data source can be a Microsoft jet database file (.mdb), an ODBC database,
such as a paradox database or an ISAM database.
 ODBCDirect workspaces allow to access database servers through ODBC, without
loading the Microsoft jet database engine

Microsoft JET Database


 Microsoft jet database is a database created with the Microsoft jet database engine.
The file name extension for a Microsoft jet database is .mdb.

Microsoft JET Database Engine


 A database management sytem that retrieves and stores data from the user and system
databases. The Microsoft jet database engine can be thought of as a data manager
component with which other data access systems, such as Microsoft Access and Visual
Basic, are built.

Data Access Object Model


 A Data Access Object is a collection of object classes that model the structure of
relational database system. They allow doing operations in the system, including
features of creating databases, defining tables, navigating and querying database.
 Visual Basic supports data access objects such as the DBEngine, workspace, data base,
tabledef, field, index and recordset objects.
The following figure shows the Data Access Objects hierarchy.

Various Data Access Object


DBEngine The DBEngine is the top-level database object and corresponds to the
jet database engine. This object is used to set database engine system
parameters and default workspace.
Workspace The workspace object is used to support simultaneous transactions and
it acts to open the databases as a container. A default workspace object
workspaces(O) is created when the data access objects are referenced in
the language at run time. The default workspace is always available and
can never be closed or removed from collection.
Object-Oriented Programming
3.52 3.51 Visual Programming

Database Database object corresponds to a jet native or external database or


a direct ODBC connection. This is used to define the database tables,
relations, stored queries to an OpenRecordset objects.
Tabledef The tabledef object corresponds to a stored table definition. Each tabledef
in a collection represent the definition of a table in the current database
or an attached table in the external database.
QueryDef The querydef object is a stored query definition, which is a precompiled
SQL statement.
Recordset The recordset object corresponds to the cursored view into a database
table or the results of a query. A cursored view is one that stores rows
of data in buffer and points to one row of data at a time called CURRENT
RECORD. The cursor may be positioned to any row of data using move, seek
or find methods.
Field The field object is a column of datatype and set of properties. Tabledef,
querydef and recordset objects have collection of field objects.
Index The index object is a stored index associated with tableDef object or table
type recordset object.
Parameter The parameter object represents a parameter associated with a querydef
object created from a parameter query. A parameter's collection contains
all the parameter objects of a querydef.
User The user object is used to define and enforce database security. The
DBEngine object supports a set of user collection. The user collection
contains all stored user objects of a workspace or group account.
Group The group object is a collection of users with similar access rights. The
DBEngine object supports a collection of system groups. Each user in the
group inherits the permissions to access the objects that the group can
access.
Relation The relation object represents a relationship between fields in table
or queries. A relation collection contains stored relation objects of a
database object. The DBEngine enforces certain update and delete
conditions on the data associated with the fields of the relation object, to
maintain referential integrity.
Object-Oriented Programming 3.53

Property A property object represents a built in characteristic of a data access


object. Properties collection contains all the property objects for a
specific instance of an object. Except for the connection and Error
objects, every DAO object has a properties collection.

Document A document object includes information about one instance type of type
of object. The object can be a database, saved table, query or relationship.
A documents collection contains all of the document objects for a specific
type of object.
A container object holds information describing the objects that are
Container grouped into that container. A container collection contains all container
objects that are defined in a database.

Accessing And Manipulating Database

1. Create Workspace Method


This method Create a new workspace object.
Syntax:
Set workspace=CreateWorkspace (name,user,password,type)
Example:
Dim wrk as workspace Dim
wrkloop as workspace
Dim prploop As property ' create an ODBCDirect workspace.
Set wrk = Createworkspace ("work", "admin", "anitha", dbuseODBC)
workspace. Append wrk
Defaulttype = DBUseJet
Debug.print "workspace objects in workspaces collection:"
For Each wrkloop in workspaces
Debug.print " " & wrkloop . Name
Next wrkloop
Object-Oriented Programming 3.54

2. CreateDatabase Method
Create a new database object, saves the database to disk, and returns an opened database
object.
Syntax:
Set database=Workspace. Createdatabase (name,locale,options)
Where
Workspace is an object variable that represents the existing workspace objects
that will contain the database. If you omit workspace, it will use the default
workspace.
Locale: a string expression that specifies a collating order for creating the
database. You must supply this argument or an error occurs. You can also create a
password for the new database object sby concatenating the password string with
a constant in the locale argument.
Example
DbLangSpanish & " : pwd = newpassword"
Locale contants
DbLangGeneral : English, German, French...
DbLangArabic : Arabic and soon.
Options: Use one of the following constants in the options argument to
specify which version the data format should have and whether or not to encrypt the
database.

Options constant
DbEncrypt Creates an encrypted database.
Dbversion 1O Creates a database that uses the Microsoft jet database engine
version 1. file format
Dbversion 11 Creates a database that uses the Microsoft jet database engine
version 2.0 file format
Dbversion 3 Creates a database that uses the Microsoft jet database engine
version 3.0 file format (default)
If you omit the encryption constant, Createdatabase creates an unencrypted data base.
Object-Oriented Programming 3.55

Example :
This example creates a new, encrypted database object.
Dim wrk as workspace
Dim db as database
Set wrk = dbeingine. workspaces ("work")
If dir ("//ntserver/vb6/kavi.mdb") <> ""then

Set db = wrk . dreatedatabase ( \\ntserver\vb6\ kavi.mdb,

_dblanggeneral, Dbencrypt)
Forml.print wrk.name
Forml.print wrk.name
Forml.print db.name
db.close
End if

3. Opendatabase Method
Opens a specified database in a workspace object and returns a reference to the database
object that represents it.
Syntax:
Set database = Workspace.OpenDatabase (dbname,options, read-only, connect)
Where,

Database An object variable that represents the database object that you want to
open.
Workspace Optional. An object variable that represents the existing workspace
object. If you don't specify it include a default workspace.
DbName A string that is the name of an existing Microsoft jet database file or the
data source name (dsn) of an ODBC data source.
Options A variant that sets various options for the database settings True: opens
the database in exclusive mode.
False: default. Opens the database in shared mode.
Object-Oriented Programming 3.56

Read-only Optional. A variant value that is True if you want to open database with
read-only access or False (default) if you want to open the database with
read/write access.
Connect Optional. A variant that specifies various connection, information,
including password.

Example
Dim wrk as workspace
Dim db as database
Set wrk=createworkspace ("","admin",'"',dbusejet)
Set db=wrk. opendatabase ("\\intserver/vb6/kavi. mdb",true)
Db.close
Wrk.close

4. Tabledef Collection
A tabledef collection contains all stored tabledef objects in the database. The default
collection of a database object is the tabledefs collection. We refer to a tabledef object in a
collection by its ordinal number or by its name property.
Example :
Tabledefs (0) or tabledefs ("name") or tabledefs! (name)

5. Tabledef Object
A tabledef object represents the stored definition of a base table or a linked table.

CreateTableDef method : This method creates a new tabledef object.

Syntax:
Set tabledef=database. Createtabledef (name, attribute, source, connect )
Where,

tabledef An object variable that represents the tabledef you want to create.
database An object variable that represents the database you want to use to create
the new tabledef object.
name Optional. A variant that uniquely names the new tabledef object.
Object-Oriented Programming 3.57
attributes Optional. A constant or combination of constant that indicates one or
more characteristics of the new tabledef object
Object-Oriented Programming 3.58

source Optional. A variant countering the name of a table in an external databases


that is the original source of data.
connect Optional. A variant containing information about the source of an open
database, a database used in a pass-through query.
You can't append a tabledef object to the tabledefs collection until you define at least one
field for the tabledef object.
Example:
Dim db as database
Dim tb as tabledef
Set db=opendatabase ("\\intserver/vb6/kavi.mdb")
Set tb=db.createtabledef ("sam")

6. Querydef Object
A Querydef object is a stored definition of a query in a Microsoft jet database, or a temporary
definition of a query in an ODBCDirect workspace .

CreatQuerydef Method : Creates a new Querydef object in a specified database object.


Syntax:
Set querydef=object. createquerydef (name,sqltext)
Where,

Querydef Name of the querydef object variable.


Object An object variable that represents an opendatabase object that will
contain the new Querydef .
Name Optional. A variant that uniquely names the new querydef.
Sqltext Optional. A variant that is an SQL statement for defining querydef.

To run the SQL statement in a querydef object, use the execute or OpenRepordset
method. To remove a querydef object from a querydefs collection in a Microsoft
Note jet database, use the delete method on the collection.
Object-Oriented Programming 3.59

Example:
Dim db as database
Dim qs as querydef
Set db=opendatabase (\\intserver/vb6/kavi.mdb)
With db
'TEMPORARY QUERYDEF WILL BE CREATED
set qs=. Createquerydef ("","select * from emp")

'PERMANENT QUERYDEF IS CREATED

set qs 1=. Createquerydef ("bquery" , "select * from stud")


forml. print. name
forml.print
qs.name
forml.print
qs1.name
Msgbox "querydef created ok",
end with
db.close
Execute method Runs an action query or executes an SQL statement on a specified connection
or database object.

7. Action query

A query that copies or changes data. Actions queries include append, delete, make table and
update queries. Delete and update queries change existing data. Append and make table
queries copy existing data. Select queries returns data records. An SQL pass through query
also an action query.
Syntax
Object. execute source, options
Querydef. execute options
Where,
Object
Object-Oriented A connection or database object variable on which the query will run.
Programming 3.60
Querydef An object variable that represents the querydef object.
Source A string that is an SQL statement for the Querydef object.
Object-Oriented Programming 3.61

Options Optional. A constant or combination of constants that determines the


data Integrity characteristics of the querydef.
Settings for options

DbDenyWrite denies write permission to other users.


Dblnconsistent default. Executes inconsistent updates.
DbConsistent executes consistent updates.
DbSqlPassThrough Executes an SQL pass_through query to pass the.
SQL statement for processing in ODBC database.
Dbfailonerror Rolls back updates if an error occurs.
Execute method is valid only for action queries.
Example:
Dim db as database
Dim sq11 as string
Dim sq1r as string
Dim qs as querydef
Sq11="update emp set eno=10 where eno=1"
Set db=opendatabase (''\\intserver/vb6/kavi.mdb")
Set qs=db.createquerydef ("", sq11)
Db.execute sq 11, dbfailonerror
Db.close

8. Field Object

A field object represents a column of data with a common data type and a common set of
properties. The fields collection of index, querydef, relation, and tabledef objects contain
the specifications for the fields. The field collection of a recordset object represents the field
objects in a row of data, or in a record.
CreateField Method
Creates a new field object in Microsoft jet workspaces only.
Syntax
Set field=object createfield (name,type, size)
Object-Oriented Programming 3.61

Where,

Field An object variable that represents the field wish to create.


Object An object variable that represents the index, relation, or tabledef object
for which you want to create the new field object.
Name An object variable that represents the index, relation, or tabledef object
for which you want to create the new field object.
Type Optional. A constant that determines the data type of the new field object.
Size Optional. A variant the indicates the maximum size in bytes of a field
object that contains text.
The type and size arguments apply only to field objects in a tabledef object. These arguments
are ignored when a field object is associated with an index or relation object.
To remove a field object from a field collection, use the delete method on the collection. You
can't delete a field object from a tabledef object's field collection after you create an index
that references the field.
Example:
This example creates a new database by using CreateDatabase and Createfield method.
Dim db as database
Dim tb as new tabledef
Dim fd as new field
Set db=DBEngine. Createdatabase (“filetb. mdb”)
Tb.name="sample"
Set fd=tb.createfield ("no", DBinteger)
Tb.fields.append. f
Set fd=tb.createfield ("name", dbtext, 15)
tb. fields. append.fd
d b. tabledefs. append. tb
Msgbox "table created"
Set db=nothing
Object-Oriented Programming 3.61

9. Index Object
 Index object specifies the order of records accessed from database tables and whether
or not duplicate records are accepted, providing efficient access to data.
 For external databases, index objects describe the indexes established for external
tables (Microsoft jet workspaces only). The Microsoft jet database engine uses indexes
when it joins tables and creates recordset objects.
 Indexes determine the order in which table-type recordset objects return records,
but they do not determine the order in which the Microsoft jet database engine stores
records in the base table with an index object,
 Use the primary and unique properties to determine the ordering and uniqueness of
the index object.

Create Index Method


 Use the Createlndex Method on a tabledef object.
 Use the CreateField method on the index object to create a field for each field to be
Included in the index object.
 Set index properties as needed.
 Append the field object to the field collection.
 Append the index object to the index collection.
Example:
To create an index on name field of the sample table.
Dim db as database
Dim tb as tabledef
Dim idx as index
Set db=opendatabase ("fileidx.mdb")
Set tb=db.tabledefs ("sample'')
Set idx=tb.createindex ("idxname")
idx. fields. append tb.createfield ("name'')
tb. indexes. append. idx
msgbox "index was created"
Db.close.
Object-Oriented Programming 3.62

10. Relation Object


 A relation object represents a relationship between fields in tables or queries in
Microsoft jet databases only.
 You can use the relation object to create new relationships and examine existing
relationships in your database.
 To add a relation object to the relations collection, first create it with the CreateRelation
method, and then append it to the relations collection with the append method. This
will save the relation object when you close the database object.
 To remove a relation object from the collection, use the delete method.

CreateRelation method
 Create a new relationship between tables using the CreateRelation method of the
database object.
 To create a new relationship, you must specify the name of the new relationship,
the tables involved in the relationship and specify which fields are linked in the
relationship.
Syntax
Set relation=db.createrelation (name,table,foreigntable,attributes)
Where, TABLE FORMAT NEEDED
Relation: the name of an object variable of type relation.
Db: a database object.
Name: the name of the relation object you're trying to create.
Table: the name of the primary table involved in the relation.
Foreigntable: the name of the foreign table involved in the relationship.
Example:
Dim db as database
Dim rel as relation
Set db=opendatabase (''filerel.mdb'')
Set rel=db.createrelation ("relcustomer")
With rel
Object-Oriented Programming 3.63

. table="customer"
. Foreigntable="order"
end with
rel.fields.append rel.createfield ("id")
rel.fields ("id"). Foreignname= "custid"
Db.relation.append rel
Msgbox "relation created"
This code creates a relationship between customer and order table. It begins by creating
a relation object using the CreateRelation method of the database object. It then creates a
field object using the create Field method of the relation object. Then set the foreign name
property of the field object to the name of the foreign key and finally append the whole
works to the relation collection. Also creates an index on foreign key field.

11. Recordset Object


 A recordset object represents the records in a base table or the records that result
from running a query.

 Recordset objects are used to manipulate data in a database at the record level. DAO
objects use recordset objects to manipulate data.

 All recordset objects are constructed using records (rows) and fields (columns).

There Are Five Types Of Recordset Objects

1.Table-type recordset
Representation in code of a base table that can use to add, modify, or delete records from a
single database table.

2.Dynaset-type recordset
The result of a query can have updatable records. A dynaset-type recordset is a Dynamic Set
of records that can use to add, delete, or change records from an underly ing database table
or tables. A dynaset-type recordset object can contain fields from one or more tables in a
database.
3.Snapshot-type recordset
A static copy of a set of records that can use to find data or generate reports. A snap shot-
type recordset object can contain fields from one or more tables but cannot be updated.
Object-Oriented Programming 3.64

4.Forward-only-type recordset
Identical to snapshot. It can scroll forward through records. This is useful when you need a
single pass through a result set is needed.
5.Dynamic-type recordset
A query result set from one or more base tables can add, change, or delete records from
a returning query. Further, records other users add, delete, or edit in the base tables, also
appear in recordset.
Table-Type Recordset Object
 To create a table-type recordset object , use the Openrecordset method on an open
database object.

 It can create a table-type recordset object from a base table of a Microsoft jet data
base, but not from an ODBC or linked table.

 It cannot be referred to more than one base table and cannot create it with an SQL
statement to filter or sort data.

 To maintain data integrity, table-type recordset objects are locked during the edit and
update methods. So that only one user can update a particular record at a time.
Openrecordset method
Creates a new recordset object and appends it to the recordset collection.
Syntax
For Connection and database objects:
Set recordset=object .Openrecordset (source,type,options,lockedits)
For querydef,recordset and tabledef objects:
Set Recordset = object.OpenRecordset (type,options,lockedits)
Settings for type argument

DbOpenTable Opens a table-type recordset object.


DbOpendynamic Opens a dynamic-type recordset object.
DbOpenDynaset Opens a dynaset-type recordset object.
DbOpenSnapshot Opens a snapshot-type recordset object.
DbOpenForwardonly Opens a forward-only-type recodset object.
Object-Oriented Programming 3.65

Delete note

Settings for options argument

Argument Description
DBAppendOnly Allows the user to append new records to the recordset, but
prevents them from editing or deleting existing records.
DBSQLPassThrough Passes SQL statements to a Microsoft jet-connected ODBC
data source for processing.
DbSeeChanges Generates a run-time error if one user is changing data that
another user is editing.
DbDenyWrite Prevents other users from modifying or adding data in a table.
DbDenyRead Prevents other users from reading data in a table.
DbOpenForwardonly Creates a forward-only recordset.
DblnConsistent Allows inconsistent updates (Microsoft jet dynaset-type and
snapshot-type recordset object only).
DbConsistent Allows only consistent updates (Microsoft jet dynaset-type
and snapshot-type Recordset objects only).

Settings for lock edit argument

DBReadOnly Prevents users from making changes to the Recordset (default


for ODBCDirect workspaces). You can use dbReadOnly in
either the options argument or the lock edits argument, but
not both. If you use it for both arguments, a run-time error
occurs.
DbPessimistic Uses pessimistic locking to determine how changes are made
to the Recordset in a multi-user environment. The page
contain ing the record you're editing is locked as soon as you
use the Edit method (default for Microsoft jet workspaces).
Object-Oriented Programming 3.66

DbOptimistic Uses optimistic locking to determine how changes are made


to the Recordset in a multi-user environment. The page
containing the record is not locked until the Update method
is executed.
DbOptimisticValue Uses optimistic concurrency based on row values (ODBCDirect
Workspaces only).
Example:
Dim db as database
Dim rs as recordset
Set db=opendatabase (''filerec.mdb")
Set rs=db.openrceordset ("emp", Dbopentable)
Methods in Recordset Object

Add New
Creates a new record for an updatable recordset object.
Syntax:
Recordset . AddNew
Example
This example adds a new record to a recordset.
Dim db as database

Dim Rs as recordset
Set db=opendatabase (“filedb. mdb")
Set rs=db.openrecordset ("emp ", dbopendynset)
With rs
. addnew
!no=1
!name="Akshay"
!desg="mgr"
!sal=5000
. update
Object-Oriented Programming 3.67

end with
rs.close
db.close

Edit

Copies the current record from an updatable recordset object to the copy buffer for
subsequent editing.
Syntax :
Recordset. Edit
Example

This example uses the edit method to replace the current data with the specified data.
Dim db as database
Dim rs as recordset
Set db=opendatabase ( “filedb.mdb'')
Set rdb.openrecordset ("emp " dbopendynaset)
No=rs! No
Name=rs! Desg
Salary=rs! Sal
Debug.print "old value"
Debug.printno & " " & name & “ “ & desg & " " & sal With
rs
. Edit
!no=12
!name="vani"
!desg="prof"
!sal=3000
. update
End with

Delete
Deletes the current record in an updatable Recordset object.
Object-Oriented Programming 3.68

Close
Closes the open DAO object.

Move
Moves the position of the current record in a recordset object. Moves to the first, last, next,
or previous record in a specified recordset object and make that record the current record.

Seek
Locates the record in an indexed table-type recordset object that satisfies the specified
criteria for the current index and makes that record the current record.
Syntax
Recordset. seek comparison, key1,key2...key13.
Where,

Comparison - One of the following string expression:<,>, <=, >=, or=.


Key1,key2...key13. - Type of comparison to be made between the columns of the index and
the corresponding KeyValues.

DAO LAB SESSION

Lab Exercise and solutions

Exercise 1.
How to access the Data from the database by using the Data Control.

Solution:
 The Below Screen will display the details of the controls description.
 Place a Frame control, four label controls, four text boxes on the form. And also place
a Data Control on a Form.
Naming Conventions & Property settings

Control Property Value


1 Text Box Text Empty
2 Label1 Caption Empcode
Object-Oriented Programming 3.69

3 Label2 Caption Empcode


4 Label3 Caption Address
5 Label4 Caption Birthdate
6 Data1 Caption Employee Details
Database Connection of Data Control :
To set the database name :
By default, Datacontrol property is connected to access
Select DatabaseName property control - select Nwind file by clicking on browse button

S e t t h e f o l l o w i n g Properties for the TextBoxes


Text 1 DataSource Data1 (Data Control name)
DataField EmployeelD (Field in the Employee table)
Text 2 DataSource Data1 (Data Control name)
DataField LastName (Field in the Employee table)
Text 3 DataSource Data1 (Data Control name)
DataField BirthDate (Field in the Employee table)
Text 4 DataSource Data1 (Data Control name)
DataField Address (Field in the Employee table)
Multiline True
ScrollBars Horzontal
After settings all the properties to the controls the Screen look like.

PASTE FIGURE : DATA CONTROL

Now Run the Application by pressing F5

In the above example, only you can view the records. You can move the records
forward & backward through by using the data control's arrow key as shown
Note in the previous screen. If you want to update or modify then follow the below
Exercise2
Object-Oriented Programming 3.71

Exercise 2.
How do you assign the records to controls by using the DAO object? Provide the
options Add, Modify,Delete,Save.
Solution:
Before going to implement the program. First Create tables in the MsAccess or SQL
Server.
Create table in MsAccess
Select Visual Data Manager from the Add_lns menu and create the following.
Table name : Employee
With Fields : Empcode, EmpName, Address, BirthDate

Steps to Design the form


1. Add a New Form to the project.
Controls in the Frame 1
2. Add Four TextBoxes Text1 ,Text2, Text3, Text4 and make it text property to empty.
3. Add four Label Boxes and set its captions as Empcode, Empname, Address,
DataofBirth
4. Add New Frame2 with Caption - Operation
5. Add six command buttons on it (within Frame control)
Object-Oriented Programming 3.72

Property settings for Command Buttons:

Command 1 Name : cmdAdd


Caption : &ADD
Command 2 Name : cmdMod
Caption : &MODIFY
Command 3 Name : cmdDel
Caption : &DELETE
Command 4 Name : cmdSave
Caption : &SAVE
Command 5 Name : cmdCan
Caption : &CANCEL
Command 6 Name : cmdAdd
Caption : &ADD

6. Add New Frame, and add four command buttons on it. (create control array).
These commands are used to move records.

Property settings for Command Buttons:


Command Name cmdMoves
CmdMoves(O) Caption <<
CmdMoves(1) Caption >>
CmdMoves(2) Caption <
CmdMoves(3) Caption >

After setting the controls, the Form looks like the below screen.

PASTE FIGURE : DAO


Object-Oriented Programming 3.73

Write the following code in the view code.


In general declarations

Dim EmpDb As Database


Dim EmpRs As Recordset
Dim SqlStr As String
Dim A As Integer

'To add New Record


Private Sub cmdAdd_ Click( )
A=1
CmdEnables (False)
EmpRs.AddNew
Text1.SetFocus
End Sub

'To clear the Texts or Cancel the records


Private Sub cmdCan_ Click( )
CmdEnables (True)
A=O
End Sub

'To Delete a Current Record


Private Sub cmdDel_ Click( )
CmdEnables (False)
A =3
End Sub

'To Exit from the Screen


Private Sub cmdExit_Click( )
EmpRs. Close
Set EmpRs = Nothing
Object-Oriented Programming 3.74
EmpDb. Close
Set EmpDb = Nothing
Unload Me
End Sub
Object-Oriented Programming 3.75

'To Modify the Record


Private Sub cmdMod_ Click( )
A=2
CmdEnables (False)
If EmpRs.EditMode = dbEdiNone Then
EmpRs.Edit
End If
End Sub

'To move the records


Private Sub CmdMoves_ Click(lndex As Integer)
On Error Resame Next
If EmpRs. RecordCount > 0 Then
If Index = O Then
EmpRs.MoveFirst
MoveFields
Elseif Index = 1 Then
EmpRs.MoveLast MoveFields
Elself Index = 2 Then
EmpRs. MoveFirst
MoveFields
Elself Index = 3 Then
EmpRs. MoveNext
MoveFields
End If
Else
MsgBox "There is no records in the Table" End If
End Sub
Object-Oriented Programming 3.76

'To Save the Record


Private Sub cmdSave_ Click( )
On Error Resume Next
If A = 1 Then
Assign_ TextTo_Recordset
EmpRs. Update
MsgBox "Records Added"
CmdEnables (True)
Elself A = 2 Then
Assign_ TextTo_Recordset
EmpRs. Update
MsgBox "Records Modified"
CmdEnables (True)
Elself A = 3 Then
EmpRs. Delete
MsgBox "Records Deleted"
CmdEnables (True)
End If
A=O
End Sub

'To Open the Database and Recordset


Private Sub Form_Load()
Set EmpDb = OpenDatabase("C:\EmpTable.mdb")

'YOU SHOULD PROVIDE THE PATH OF YOUR DATABASE


Set EmpRsEmpDb. OpenRecordset("employee ")
ClearTexts ' this procedure to clear all the Text boxes
If EmpRs. RecordCount > O Then
Assign_recordset_to_Text 'this procedure to assign the
Object-Oriented Programming 3.77

'recordset values to to Text boxes


Else

MsgBox "First time there is No Records in table" & vbCrlf _


& "You -should Add Now", vblnformation, "Employee"
End If
CmdEnables (True)
End Sub

'Assign the Records to the Text boxes (Calling Procedure)


Private Sub Assign_recordset_to_ Text( )
If Not lsNull(EmpRs.Fields("empcode")) Then
Text1.Text = UCase(EmpRs(O))
End If
If Not lsNull(EmpRs.Fields("empname")) Then
Text2.Text = UCase(EmpRs(1))
End If
If Not lsNull(EmpRs.Fields("address")) Then
Text3.Text = UCase(EmpRs(2))
End If
If lsDate(EmpRs.Fields("dob")) Then
Text4.Text = Format(EmpRs(3), "dd/mm/yyyy") End If
End Sub

'Clearing the Text boxes (Calling Procedure)


Private Sub ClearTexts( )
If A <> 2 And A <> 3 Then
Text1. Text = " "
Text2. Text = " "
Text3.Text = " "
Object-Oriented Programming 3.78

Text4.Text = ""
End If
End Sub

'Moving fields (Calling Procedure)


Private Sub MoveFields( )
On Error Resume Next
Text1 = EmpRs(O)
Text2 = EmpRs(1)
Text3 = EmpRs(2)
Text4 = EmpRs(3)
End Sub

'Enabling & disabling command buttons (Calling Function)


Public Function CmdEnables(CdFlag As Boolean)
Frame3. Enabled = CdFlag
cmdAdd.Enabled = CdFlag
cmdMod. Enabled = CdFlag
cmdDel. Enabled = CdFlag
Fram .Enabled = Not CdFlag
cmdSave.Enabled = Not CdFlag
cmdCan. Enabled = Not CdFlag
Clear Texts
End Function

'Assigning the text values to Recordset fields (Calling Procedure)


Private Sub Assign_ TextTo_Recordset( )
If Text1 <> " " Then
EmpRs(O) = UCase(Trim(Text1))
Object-Oriented Programming 3.79

End If
If Text2 <> " " Then
EmpRs(1) = UCase(Trim(Text2))
End If
If Text3 <> " " Then
EmpRs(2) = UCase(Trim(Text4))
End If
If lsDate(Format(CDate(Text3), 11dd/mm/yyyy " )) Then
EmpRs(3) = Format(Text3, "dd/mm/yyyy'')
E
N
D
I
F
E
N
D
S
U
B
Exercises : (Self Assessment)
Create a table in Access as "Employee 1"

Fields DateType Size


Empno Integer Default
EName Text 50
Basic Currency Default
DA Currency Default
DOB Date/Time Default
Phone Text Default
Generate from you VB application : Empno should be update automatically the
next number of the Previous Employee. The DOB accept minimum age of the
staff should be 21 years old. In VB application provide a Grand salary label to
display the grand total salary (Basic + DA).
àààà

You might also like