Module/Unit: 2
9.0 LINKING TO DATABASES
Specific Objectives
By the end of this topic, the trainee should be able to:
1. Apply database controls
2. Create reports
CONTENT
Database controls
Reports
Data Access Programming Models
Visual Basic is also addressed as an RDE (Rapid Development Environment), because it
offers various Data Access programming models.
They include:
1. DAO - Data Access Objects
2. RDO - Remote Data Objects
3. ADO - Active Data Objects
DAO - Data Access Objects
A Databases collection contains all Database objects opened or created in a Workspace
object. A Workspace object defines a named session for a user. It contains open databases
and provides mechanisms for simultaneous transactions.
1
Prepared by Mr G. Muthuri
Module/Unit: 2
DBEngine The DBEngine object is the top level object in the DAO object model.
Workspaces A Workspaces collection contains all active, unhidden Workspace
objects of the DBEngine object.
Workspace A Workspace object defines a named session for a user.
Connections A Connections collection contains the current Connection objects of a
Workspace object.
Databases A Databases collection contains all open Database objects opened or
created in a Workspace object.
Groups A Groups collection contains all stored Group objects of a Workspace
or user account (Microsoft Jet workspaces only).
Users A Users collection contains all stored User objects of a Workspace or
Group object. (Microsoft Jet workspaces only).
RDO - Remote Data Objects
Remote Data objects and collections provide a framework for using code to create and
manipulate components of a remote ODBC database system. Objects and collections have
properties that describe the characteristics of database components and methods that you use
to manipulate them. Using the containment framework, you create relationships among
objects and collections, and these relationships represent the logical structure of your
database system.
Below are RDO objects
1. rdoEngine- The rdoEngine object represents the remote data source. As the top-level
object, it contains all other objects in the hierarchy of Remote Data Objects (RDO).
2. rdoEnvironment - An rdoEnvironment object defines a logical set of connections
and transaction scope for a particular user name
3. rdoconnection- An rdoConnection object represents an open connection to a remote
data source and a specific database on that data source, or an allocated but as yet
unconnected object, which can be used to subsequently establish a connection.
4. rdoQuery- The rdoQuery object is used to manage SQL queries requiring the use of
input, output or input/output parameters.
5. rdocolumn- An rdoColumn object represents a column of data with a common data
type and a common set of properties.
6. rdoParameter- An rdoParameter object represents a parameter associated with an
rdoQuery object.
7. rdoresultset- An rdoResultset object represents the rows that result from running a
query rdotable - An rdoTable object represents the stored definition of a base table or
an SQL view.
8. rdopreparedstatement- An rdoPreparedStatement object is a prepared query
definition.
2
Prepared by Mr G. Muthuri
Module/Unit: 2
ADO - ActiveX Data Objects
The new Data Access Programming model in Visual Basic 6.0 is the ADO.
The bridge between the data providers and data consumers is through data sources created
using Microsoft ActiveX Data Objects (ADO), which is the primary method in Visual Basic
to access data in any data source, both relational and non-relational.
The ActiveX Data Objects, consists of seven independent objects.
1. Connection Object - Represents a unique session with a data source.
2. Recordset Object - Represents records from a data provider like altering the records
in a table.
3. Field Object - Represent an individual field in a recordset.
4. Command Object - Represents a command. For example to execute a stored
procedure or a parameterized query.
5. Parameter Object - Represents an individual parameter in a stored procedure or a
parameterized query.
6. Property Object - Represents data - provider - specific properties.
7. Error Object - Represents ADO Errors.
Data Access Choices
We can access data in an external database by attaching the external database or by opening it
directly.Attaching a Table to Microsoft Jet Database.When an external database is attached to
a Microsoft Jet database, the table's data remains in the external database. However, the
connection information and table definition are stored in the Microsoft Jet database. We see
the table as we would any other Microsoft Jet database table, except that we cannot create a
table-type recordset in an attached table. We can use Microsoft Access to easily attach a table
to a Microsoft Jet Database.
Accessing ODBC Databases
DAO version 3.5 introduces a new client/server connection technology named Open
Database Connectivity Direct (ODBCDirect). This technology establishes a connection
directly to an ODBC data source, without loading the Microsoft Jet database engine.
Defining an ODBCDirect Workspace
The technology of ODBCDirect enables us to access ODBC data sources directly by using
data access objects (DAO). We can use the features of this client/server connection to access
a database quickly without loading the Microsoft jet database engine.
The first step in using ODBCDirect is to define the type of workspace we will use. We can do
this in one of two ways: by setting the default workspace type, or by defining a specific
workspace type as ODBCDirect.
Microsoft Jet Database Engine Locking
All database management systems provide some sort of locking mechanism to prevent two
users from updating data at the same time.
The Microsoft Jet database engine provides page-level locking. Pages are blocks of records
that are 2048 bytes in size. VB stores as many records as will fit on each page. When VB
locks the page containing a record you're editing, all the other records on that page will also
be locked.
3
Prepared by Mr G. Muthuri
Module/Unit: 2
Pessimistic Vs. Optimistic Locking
The value of the LockEdits property of the Recordset object determines when a lock is placed
on the records in a recordset.
Pessimistic Locking
If the LockEdits property is True, pessimistic locking is in effect. The page containing the
current record is locked as soon as we use the Edit method. The page is unlocked when we
use the Update method.
The default locking strategy locks records for a longer period of time, but ensures that once
the Edit method has been executed, another user cannot change the data.
Optimistic Locking
If the LockEdits property is False, optimistic locking is in effect. The page containing the
record is locked only while the record is being updated.
Locks are in place for a shorter period of time, and multiple users can use the Edit method
without locking the page. However, when we use optimistic locking, we will need to handle
possible errors when the user executes the Update method.
If we do not expect users to attempt to modify the same record very often, consider setting
LockEdits to False.
ADO Data Control
The ADO (ActiveX Data Object) data control is the primary interface between a Visual
Basic application and a database. It can be used without writing any code at all to make the
connection! Or, it can be a central part of a complex database management system.
The data control (or tool) can access databases created by several other programs besides
Visual Basic (or Microsoft Access). Some other formats supported include Btrieve, dBase,
FoxPro, and Paradox databases.
Data Control Properties:
1. Align Determines where data control is displayed.
2. Caption Phrase displayed on the data control.
3. ConnectionString Contains the information used to establish a connection to a
database.
4. LockType Indicates the type of locks placed on records during editing (default
setting makes databases read-only).
5. Recordset A set of records defined by a data control’s ConnectionString and
RecordSource properties. Run-time only.
6. RecordSource Determines the table (or virtual table) the data control is
attached to.
NB//as a rule, you need one data control for every database table, or virtual table, you need
access to. One row of a table is accessible to each data control at any one time. This is
referred to as the current record.
When a data control is placed on a form, it appears with the assigned caption and four arrow
buttons:
4
Prepared by Mr G. Muthuri
Module/Unit: 2
The arrows are used to navigate through the table rows (records). As indicated, the buttons
can be used to move to the beginning of the table, the end of the table, or from record to
record.
Data Links
After placing a data control on a form, you set the ConnectionString property. The ADO
data control can connect to a variety of database types. There are three ways to connect to a
database:
1. Using a data link
2. Using an odbc data source
3. Using a connection string.
Assigning Tables
Once the ADO data control is connected to a database, we need to assign a table to that
control. Recall each data control is attached to a single table, whether it is a table inherent to
the database or the virtual table we discussed. Assigning a table is done via the
RecordSource property.
Tables are assigned by making queries of the database. The language used to make a query is
SQL.
Click on the ellipsis next to RecordSource in the property box. A Property Pagesdialog box
will appear. In the box marked Command Text (SQL), type this line:
SELECT * FROM TableName
This will select all fields (the * is a wildcard) from a table named TableName in the
database. Click OK.
Bound Data Tools
Most of the Visual Basic tools we’ve studied can be used as bound, or data-aware , tools (or
controls). That means, certain tool properties can be tied to a particular database field. To use
a bound control, one or more data controls must be on the form.
Some bound data tools are:
1. Label Can be used to provide display-only access to a specified text data field.
2. Text Box Can be used to provide read/write access to a specified text data field.
3. Check Box Used to provide read/write access to a Boolean field.
4. Combo Box Can be used to provide read/write access to a text data field.
5. List Box Can be used to provide read/write access to a text data field.
6. Picture Box Used to display a graphical image from a bitmap, icon, or metafile on
your form. Provides read/write access to a image/binary data field.
5
Prepared by Mr G. Muthuri
Module/Unit: 2
7. Image Box Used to display a graphical image from a bitmap, icon, or metafile on
your form (uses fewer resources than a picture box). Provides read/write access to an
image/binary data field.
Bound Tool Properties:
1. DataChanged Indicates whether a value displayed in a bound control has changed.
2. DataField Specifies the name of a field in the table pointed to by the respective
data control.
3. DataSource Specifies which data control the control is bound to.
There are four methods used for moving in a database. These methods replicate the
capabilities of the four arrow buttons on the data control:
1. MoveFirst Move to the first record in the table.
2. MoveLast Move to the last record in the table.
3. MoveNext Move to the next record (with respect to the current record) in the
table.
4. MovePrevious Move to the previous record (with respect to the current record) in
the table.
To create our DBMS, we need to define a few more programmatic control methods
associated with the data control Recordset property. These methods are:
1. AddNew
A new record is added to the table. All fields are set to Null and this record is made the
current record. Update saves the current contents of all bound tools.
To add a record to the database, we invoke the AddNew method. The syntax for our example
data control is:
dtaExample.Recordset.AddNew
Update
2. Refresh
After adding a record to a database, you should invoke the Refresh property of the data
control to insure proper sorting (established by RecordSource SQL statement) of the new
entry. The format is:
dtaExample.Refresh
3. Delete
To delete a record from the database, make sure the record to delete is the current record.
Then, we use the Delete method. The syntax for the example data control is:
dtaExample.Recordset.Delete
Once we execute a Delete, we must move (using one of the ‘Move’ methods) off of the
current record because it no longer exists and an error will occur if we don’t move. This gets
particularly tricky if deleting the last record (check the EOF property). If EOF is true, you
must move to the top of the database (MoveFirst). You then must make sure there is a valid
record there (check the BOF property).
6
Prepared by Mr G. Muthuri
Module/Unit: 2
Creating a Data Report
Data Report in Microsoft Visual Basic 6.0
The Microsoft Data Report designer is a versatile data report generator that features the
ability to create hierarchical reports. Used in conjunction with a data source such as the Data
Environment designer, you can create reports from several different relational tables. To
create data report in VB6.0 use the Data Environment designer.
Features of Data Report Designer
The Data Report designer has several features:
1. Drag-and-Drop Functionality for Fields—Drag fields from the Microsoft Data
Environment designer to the Data Report designer. When you do this, Visual Basic
automatically creates a text box control on the data report and sets the DataMember
and DataField properties of the dropped field. You can also drag a Command object
from the Data Environment designer to the Data Report designer.
2. In that case, for each of the fields contained by the Command object, a text box
control will be created on the data report; the DataMember and DataField property for
each text box will be set to the appropriate values.
3. Toolbox Controls —The Data Report designer features its own set of controls. When
a Data Report designer is added to a project, the controls are automatically created on
a new Toolbox tab named DataReport. Most of the controls are functionally identical
to Visual Basic intrinsic controls, and include a Label, Shape, Image, TextBox, and
Line control. The sixth control, the Function control, automatically generates one of
four kinds of information: Sum, Average, Minimum, or Maximum.
4. Print Preview—Preview the report by using the Show method. The data report is then
generated and displayed in its own window.
5. Print Reports—Print a report programmatically by calling the PrintReport method.
When the data report is in preview mode, users can also print by clicking the printer
icon on the toolbar.
6. File Export—Export the data report information using the ExportReport method.
Formats for export include HTML and text.
7. Export Templates—You can create a collection of file templates to be used with the
ExportReport method. This is useful for exporting reports in a variety of formats, each
tailored to the report type.
7
Prepared by Mr G. Muthuri
Module/Unit: 2
Data Report Controls
When a new Data Report designer is added to a project, the following controls are
automatically placed in the Toolbox tab named DataReport:
1. TextBox Control (RptTextBox)—allows you to format text, or assign a DataFormat.
2. Label Control (RptLabel)—allows you to place labels on the report to identify fields
or sections.
3. Image Control (RptImage)—enables you to place graphics on your report. Note that
this control cannot be bound to a data field.
4. Line Control (RptLine)—lets you draw rules on the report to further distinguish
sections.
5. Shape Control (RptShape)—enables you to place rectangles, triangles, or circles (and
ovals) on a report.
6. Function Control (RptFunction)—a special text box that calculates values as the
report is generated.
Adding a Data Environment
At design time, you can use the Data Environment designer to create a DataEnvironment
object. The DataEnvironment object can include Connection and Command objects,
hierarchies (relationships between Command objects), groupings, and aggregates.
Project with database and report generated (Example)
Create a database named StudentRecord using MS Access 2003. If you are using the latest
MS Office package you can save as the select the Access 2002-2003.
Create a table named Registration with the following fields.
FIELD DATA TYPE DESCRIPTION
ADMNO NUMBER PRIMARY KEY
STUDNAME TEXT
COURSE TEXT
DOB DATE/TIME
Populate the table with at-least 10 record.
Open visual basic 6.0 application and use standard EXE to create a project. Save the project
and form with an appropriate name.
ADO control is not by default on the tool box. To add it, right click on the toolbox the click
on components. The window below will appear.
8
Prepared by Mr G. Muthuri
Module/Unit: 2
On control tab scroll down until you find Microsoft ADO Data Control 6.0 (OLEDB). Tick
on the box to select, then click apply the cancel to add the ADO control. The control will now
be available on the tool box and you can add the normal way you add any other control by
double clicking or click and draw.
After adding the control right click on it (ADODC) then select on ADODC properties. The
window below will appear.
ADODC has 3 ways to connect database with the application. In this example we will use
(Use Connection String). To link click on Build button. The window below will appear for
connection.
Select the data provider (Microsoft Jet 4.0 OLED DB Provider) and click next to get the next
screen above. Select the database that we created earlier (StudentRecord) to connect. Click on
the Test Connection to test if connection was successful, and then click ok to exit that
window.
9
Prepared by Mr G. Muthuri
Module/Unit: 2
Back to the ADODC property move to the RecordSource tab to link the table that we created
on our database. On Command Type select adcmdTable then select table Registration. That
we created. See below image
Click Apply the ok to finish connecting the database. Up to that point the database is linked
to application.
Linking controls to database fields.
To display database information we need to add control such as textbox that will be used to
display the records.
Add 4 textbox and 4 labels on your form designer as shown below
To bind the control to the database fields we will use 2 main properties of the controls (data
source and data field) NB// you can use other properties too. Data source select name of our
ADODC which is Adodc1 the then data field choose depend with which field will be
displayed by that control. Bind all textbox control. Labels were used just to show which field
is where. After that you can run the application. If you have done it right the database fields
should now display on the application like below depending with record that you entered.
10
Prepared by Mr G. Muthuri
Module/Unit: 2
Modifying record from the application
To modify database we will need number of button to add new record, save, delete and
others.
add
Database commands for manipulating database
Add new Entry to database
Private Sub CmdAddNew_Click()
MsgBox "enter the names"
Adodc1.Recordset.AddNew
End Sub
To search for a record in Database
Private Sub CmdSearch_Click()
Adodc1.Recordset.Find "IDNO=" &Val(Text5.Text)
If Adodc1.Recordset.EOF Then
MsgBox ("Record NOT Found")
End If
End Sub
To Save a New record or Edited record
Private Sub CmdSave_Click()
Adodc1.Recordset.Fields("ID NO") = Text1.Text
Adodc1.Recordset.Fields("SUDENT NAME") = Text2.Text
Adodc1.Recordset.Fields("COURSE") = Text3.Text
Adodc1.Recordset.Fields("YOB") = Text4.Text
Adodc1.Recordset.Update
End Sub
11
Prepared by Mr G. Muthuri
Module/Unit: 2
To delete a Record
Private Sub CmdDelete_Click()
Confirm = MsgBox("Are you sure you want to delete this record?", vbYesNo, "Deletion
Confirmation")
If Confirm = vbYes Then
Adodc1.Recordset.Delete
MsgBox "Record Deleted!", , "Message"
Else
MsgBox "Record Not Deleted!", , "Message"
End If
End Sub
To cancel the record
Private Sub CmdCancel_Click()
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
End Sub
Move to Previous Record
Private Sub CmdPrevious_Click()
If Not Adodc1.Recordset.BOF Then
Adodc1.Recordset.MovePrevious
If Adodc1.Recordset.BOF Then
Adodc1.Recordset.MoveNext
End If
End If
End Sub
Move to next record
Private Sub CmdNext_Click()
If Not Adodc1.Recordset.EOF Then
Adodc1.Recordset.MoveNext
If Adodc1.Recordset.EOF Then
Adodc1.Recordset.MovePrevious
End If
End If
End Sub
12
Prepared by Mr G. Muthuri