Database Connectivity: Data Access Objects (DAO)
Database Connectivity: Data Access Objects (DAO)
Database Connectivity: Data Access Objects (DAO)
51
DATABASE CONNECTIVITY
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.
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
_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.
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
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 .
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")
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
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,
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.
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.
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).
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
Delete note
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).
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,
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
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
6. Add New Frame, and add four command buttons on it. (create control array).
These commands are used to move records.
After setting the controls, the Form looks like the below screen.
Text4.Text = ""
End If
End Sub
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"