0% found this document useful (0 votes)
21 views

Database

This document discusses how to access and manage databases using Visual Basic's data control. The data control allows a VB application to connect to a database, open tables, add/modify/delete records, and pass data to bound controls on a form. It connects the application to the database engine, passing information between them. The data control's properties like RecordSource and DataField are used to specify the database table and fields to interact with.

Uploaded by

gladys temwo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Database

This document discusses how to access and manage databases using Visual Basic's data control. The data control allows a VB application to connect to a database, open tables, add/modify/delete records, and pass data to bound controls on a form. It connects the application to the database engine, passing information between them. The data control's properties like RecordSource and DataField are used to specify the database table and fields to interact with.

Uploaded by

gladys temwo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 95

database

• A database is a collection of information. This


information is stored in a very structured
manner.
• The smallest unit in a database is called a field
(data item). •
• A record is a collection of fields.
• A table (file) is a collection of records.
• A database is a collection of one or more tables.
database management system (DBMS).

• each database requires some way for a user to


interact with the information within. Such
interaction is performed by a database
management system (DBMS).
The tasks of a DBMS are really quite simple

• 1.View the data


• 2. Find some data of interest
• 3. Modify the data
• 4. Add some data
• 5. Delete some data
Examples of DBMS
• Programs like Access (a Microsoft product)
and Oracle
• A Visual Basic application cannot directly
interact with a database.
• There are two intermediate components
between the application and the database:
the data control and the database engine:
data control
• The data control is a Visual Basic object that
connects the application to the database via
the database engine.

• It is the conduit between the application and


the engine, passing information back and forth
between the two.
Data control cont’
• The Data control is a link between the
information in your database and the Visual
Basic control that you use to display the
information. E.g a textbox
DATA BOUND CONTROL
• A data-bound control, such as a list box, a grid
or a text box, is a control that is hooked up to
a data source.
Data control Data-bound

Using data control is a two-step process. You create the controls, such as labels
First you place a data control on a form and text boxes, to display the actual data.
and set the properties to link it to a Each control is a bound to particular field
database file and table in the table. In this example the label is
called a data bound control and
automatically displays the contents of
bound field when the project runs.

Data control generally links one form with If you want to have data-bound controls on
one table. second form, you must place a data
control on that form.

Prefix of data control is “dat” For data-bound control prefix depends


upon the control which you are using.
database engine
• The database engine is the heart of a Visual
Basic database management system.
• It is the actual software that does the
management. Having this engine saves
programmers a lot of work. The database
engine native to Visual Basic is known as the
Jet engine.
database accessing methods are as follows;

• Jet Engine - Accessing Microsoft Access and


Visual Basic databases.
• 2. ODBC (Open Database Connectivity) - Allow
access to the client server databases on a
network.
• 3. ISAM (Index Sequential Access Method) -
Used to access flat databases such as dBase,
FoxPro, ParaDox.
Visual Data Manager
• The Visual Data Manager is a Visual Basic
Add-In that allows the creation and
management of databases.
Functions of visual data manager

• Create a new database


• Open existing databases
• Add data tables to a database
• Link to information contained in other databases
• Add fields and indexes to a database
• Set relationships between data tables
• Enter and find data in data tables
• Enter and save SQL statements
• Compact and repair databases
• Encrypt and decrypt databases
Data Access
• Data access is a feature of Visual Basic that allows
you to access and manipulate any database from
Visual Basic. The database may be either MS-
Access database or FoxPro database or it may also
be any of the relational databases such as Oracle.
• Visual Basic provides three data access interface
1. DAO(Data Access Object)
2. RDO(Remote Data Object)
3. ADO(Active X Data Object)
Functions of Data Access Control
• 1. Connect to a database.
• 2. Open a specified database table.
• 3. Create a virtual table based on a database query.
• 4. Pass database fields to other Visual Basic tools,
for display or editing. Such tools are bound tools
(controls), or data aware.
• 5. Add new records or update a database.
• 6. Trap any errors that may occur while accessing
data.
• 7. Close the database.
DATA CONTROL PROPERTIES
• Align Determines where data control is displayed.

• Caption Phrase displayed on the data control.

• ConnectionString Contains the information used to


establish a connection to a database. E.g. Provider
= Microsoft.Jet.OLEDB.4.0;Data Source=C:\
Program Files (x86)\Microsoft Visual Studio\VB98\
BIBLIO.MDB;Persist Security Info=False
• LockType Indicates the type of locks placed on
records during editing (default setting makes
databases read-only).

• Recordset A set of records defined by a data


control‘s ConnectionString and RecordSource
properties. Run-time only. RecordSource
Determines the table (or virtual table) the data
control is attached to.
Parts of a data control
Data Bound Tools
• Most of the Visual Basic tools we‘ve studied can be used
as bound, or data-aware, tools (or controls).
• Label - Can be used to provide display-only
access to a specified text data field.
• Text Box - Can be used to provide read/write
access to a specified text data field. Probably,
the most widely used data bound tool.
• Check Box - Used to provide read/write
access to a Boolean field.
bound controls
• Combo Box - Can be used to provide read/write
access to a text data field.
• List Box - Can be used to provide read/write
access to a text data field.
• 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.
Bound Tool Properties:
• DataChanged - Indicates whether a value
displayed in a bound control has changed.

• DataField - Specifies the name of a field in the


table pointed to by the respective data control.

• DataSource - Specifies which data control the


control is bound to.
ways of access database.

• Data Access Objects (DAO)-used to access only local


database which is a disadvantage
• This is an object model that has a collection of objects
using which you can access a database. This model
gives complete control on the database. This model
uses Jet Engine, which is the native database engine
used by Visual Basic and MS-Access. This was the first
model to be used in Visual Basic. Though it is possible
to access any database using this, it is particularly
suitable for MS-Access database and not suitable for
ODBC data sources such as Oracle and MS-SQL Server.
Remote Data Objects (RDO)

• These objects are only used to access ODBC data


sources such as Oracle.
• ODBC (Open Database Connectivity)
• These objects access databases that are on remote
machine (database server). This object model has
less number of objects compared with DAO and
more suitable for accessing remote databases.
ActiveX Data Objects (ADO)

• The ADO Recordset object is used to hold a set of records from a database
table. A Recordset object consist of records and columns (fields). In ADO,
this object is the most important and the one used most often to
manipulate data from a database.

• This object model has very few objects and it is based on OLE DB interface.
OLE DB interface is a new interface (replacing ODBC and others), through
which you can access data of all formats in the same manner.

• ADO uses OLE DB providers to access the data. That means each database
is accessed through OLE DB provider. And ADO provides the programming
framework to access OLE DB. ADO is also much easier to deal with.
The data control can be used to perform
the following tasks:
• Connect to a database.
• 2. Open a specified database table.
• 3. Create a virtual table based on a database query.
• 4. Pass database fields to other Visual Basic tools, for
display or editing. Such tools are bound tools
(controls), or data aware.
• 5. Add new records or update a database.
• 6. Trap any errors that may occur while accessing data.
• 7. Close the database.
Data Control Properties:

• Align Determines where data control is displayed.

• Caption Phrase displayed on the data control.

• ConnectionString Contains the information used to establish a


connection to a database.

• LockType Indicates the type of locks placed on records during


editing (default setting makes databases read-only).

• Recordset A set of records defined by a data control’s


ConnectionString and RecordSource properties. Run-
time only.

• RecordSource Determines the table (or virtual table) the data control
is attached to.
DataSource
• The DataSource is the name of the data
control on the form (it should already be
configured), and the
DataField
• DataField is the name of the particular field in
the database that should be displayed in the
control (this field will be in the table that was
chosen for the RecordSource of the data
control).
DATABASE ACCESS WITH THE DATA CONTROL

• STEPS:
• 1. Open a new Visual Basic project.

• 2. Put a data control (an intrinsic control,
located in the VB toolbox) on the form and set
the properties as follows:
PROPERTIES OF DATA CONTROL

Property Value

(Name) datAuthors

Caption Use the arrows to view the data

Connect Access (default)

DatabaseName ..\biblio.mdb

DefaultType UseJet (default)

RecordSource Authors (choose from list)


POINT TO NOTE
• When you use the Data Control in a project,
the properties that must be set are
DatabaseName and RecordSource, in that
order. DatabaseName is the name of the
database you want to use, and the
RecordSource is the name of the table in
that database that you want to use.

BOUND CONTROLS
• On your form, create a text box for each
field in the Authors table, with labels. (If
you were to open the database in Access,
you would see that the three fields of the
Authors table are Au_ID, Author, and Year
Born.) Set the properties of the three
textboxes as follows:
EXAMPLE

Name DataSource DataField

txtAuthID datAuthors Au_ID

txtAuthor datAuthors Author

txtYearBorn datAuthors Year Born


• When you want a control (such as a text box)
to display data from a database, the
properties that must be set are DataSource
and Datafield. The DataSource is the name
of the data control on the form (it should
already be configured), and the DataField is
the name of the particular field in the
database that should be displayed in the
control (this field will be in the table that was
chosen for the RecordSource of the data
control).
• 4. Save and run the project. Use the
arrows on the data control to scroll through
the data.

METHODS OF THE RECORDSET
OBJECT
1. MoveFirst,
2. MovePrevious,
3. MoveNext,
4. MoveLast
USING THE BOFACTION AND EOFACTION PROPERTIES OF THE DATA CONTROL

• EOF (End Of File) is a Boolean property of


the recordset object that becomes true when
an attempt is made to move forward past the
last record in a recordset.

• BOF (Beginning Of File) is a Boolean
property of the recordset object that becomes
true when an attempt is made to move
backward past the first record in a recordset.
• Click once on the data control and make
sure that the following properties are set:

• BOFAction = 0 – Move First
EOFAction = 0 – Move Last
code in the cmdMoveNext_Click() event:


• datAuthors.Recordset.MoveNext
If datAuthors.Recordset.EOF =
True Then
datAuthors.Recordset.MoveLast
• End If
AddNew method of the recordset object

• causes all the bound controls to be


cleared so that the user can enter data
ADDNEW CODE
• datAuthors.Recordset.AddNew
cmdSaveRecord.Enabled = True
• cmdMoveFirst.Enabled = False
cmdMoveLast.Enabled = False
cmdMovePrevious.Enabled = False
cmdMoveNext.Enabled = False
•cmdDeleteRecord.Enabled =
False
cmdNewRecord.Enabled = False
SAVE BUTTON
• datAuthors.Recordset.Update
cmdSaveRecord.Enabled = False
• cmdMoveFirst.Enabled = True
cmdMoveLast.Enabled = True
cmdMovePrevious.Enabled = True
cmdMoveNext.Enabled = True
•cmdDeleteRecord.Enabled = True
•cmdNewRecord.Enabled = True
Delete method
• On Error GoTo Delete_Error

• If MsgBox("Are you sure you want to delete this record?", _
• vbQuestion + vbYesNo + vbDefaultButton2, _
• "Confirm") = vbNo Then
• Exit Sub
• End If

• 'delete the current record
• datAuthors.Recordset.Delete

• 'move to a valid record
• cmdMoveNext_Click

• Exit Sub

• Delete_Error:
• ' This error will occur if you attempt to delete an author that is related to
• ' another table in the biblio.mdb database ...
• MsgBox "This record cannot be deleted. Error code = " _
• & Err.Number & vbCrLf & Err.Description, _
• vbCritical, "Cannot Delete"
DATABASE CONNECTION USING ADO
• ADO control. ADO stands for ActiveX data
objects. As ADO is ActiveX-based, it could
work in different platforms (different
computer systems) and different programming
languages.
ADDING MICROSOFT ADO DATA CONTROL 6.0 (OLEDB)
COMPONENT

• 1. Click project on the menu. From the


dropdown click Components
2. From the pop up window select
“Microsoft ADO Data Control 6.0 (OLEDB)”.
3. Click Apply then OK
• 5. Click Adodc Tool and add it to the form as
Shown Below
Configuring ADODC to connect to Access
Database
• Right Click on Adodc1 and select ADODC
Properties as shown below.
2. From the Property Pages “Using
connection String” Click on Build
From the Data Link Properties Window select “Microsoft Jet 4.0
OLE DB Provider”
Click the Next Button connect to the
database as shown below.
• Browse to select the database and Test the
connection to confirm that it succeeds.
• 6. From the “Microsoft Data Link” Click “OK”
The Connection string is now created. Apply
and Click OK
Main Objects of ADODC
• The ADO object model defines a collection of
programmable objects that can be used by
any of the Microsoft Visual languages
The Connection Object
• To establish connections between the client
and database server
• ConnectionString Property
– a long string with several attributes separated by
semicolons
– “Provider = Microsoft.Jet.OLEDB.4.0; Data
Source=C:\Program Files\VB98\Nwind.mdb”
– “Provider=SQLOLEDB.1;User ID=sa; password=;
Initial Catalog=Northwind; Data
Source=EXPERTNEW”
The Connection Object

• Open Method
– CN.open
– The open method accepts a number of
optional arguments (ConnString, UserID,
password, options)
• Close Method
– CN.Close
– Set CN = Nothing (remove the Connection
Object from memory)
Connection Example
Dim dbcon as ADODB.Connection
Set dbcon = New ADODB.Connection
dbcon.ConnectionString _
="Provider=MSDASQL.1;Persist Security _
Info=False;Data Source=NWIND"
dbcon.ConnectionTimeout = 10
dbcon.Open

dbcon.close
Set dbcon = Nothing
The Command Object

• to issue commands, such as SQL queries


and updates, to the database
• ActiveConnection Property
– If ActiveConnection is set with a reference to a
Connection Object, the Command object uses
an exiting connection.
– If ActiveConnection is set with a connection
string, a new connection is established.
CommandTypeEnum

• adCmdStoreProc The command is the name


of a Stored procedure
• adCmdTable The command is a table’s name.
“Select * from table_name” is passed to the server
• adCmdTableDirect The command is a table’s
name. More efficient that adCmdTable option
• adCmdText The command is a SQL statement
• adCmdUnknown The command is unknown
(default)
Command Example
Dim cmd As ADODB.Command
Dim rst As ADODB.Recordset

Set cmd = New ADODB.Command


cmd.CommandText = "select distinct ShipCountry from
orders"
cmd.CommandType = adCmdText
Set cmd.ActiveConnection = dbcon
Set rst = New ADODB.Recordset
Set rst = cmd.Execute
Record set
• A recordset is a data construct provided by the Jet
database engine. It is conceptually similar to a
table but includes some important distinctive
properties of its own.
• the ADO Recordset object is used to contain the
set of data extracted from a database.

The Recordset object is composed of records


(which are also referred to as rows) and of fields
(which are also referred to as columns).
Types of record sets
• When you work with recordsets in the Jet
database engine each recordset is represented as
an object conceptually similar to the user-
interface objects (such as command buttons and
text boxes) that you might have worked with in
Visual Basic in the past. Just like other types of
Visual Basic objects recordset objects have their
own properties and methods.
Recordset objects
• To view and manipulate the results of the query
• Open Method
– To execute a query
– open ( [Source], [ActiveConnection], [CursorType As
CursorTypeEnum = adOpenUnspecified], [LockType As
LockTypeEnum = adLockUnspecified], [Options As Long = -1]))
– Source can be a sql statement, a valid command object, a
table name, a query name (Access), a stored procedure name
(SQL Server)
– Options is a constant that indicates how the provider should
evaluate the Source argument if it represents something other
than a Command object
• In the Data control you set the type of
recordset in the Data control’s RecordsetType
property.
• When creating recordsets in code you set the
type of recordset when you create it
ADO CursorLocation
• Sets or returns a long value that is a
CursorLocationEnum value which defines the
location of the cursor engine (server-side or
client-side).
• The CursorLocation property sets or returns
one of the CursorLocationEnum constants
that specifies the location of the cursor library.
CURSOR LOCATION CONT’
• Every cursor uses temporary resources to hold its
data.
• These resources can be memory, a disk paging file,
temporary disk files, or even temporary storage in
the database.
• The cursor is called a client-side cursor when these
resources are located on the client computer.
• The cursor is called a server-side cursor when these
resources are located on the server.
CURSOR LOCATION
• adUseNone:OBSOLETE (appears only for backward
compatibility). Does not use cursor services
• adUseServer Default. Uses a server-side
cursor
• adUseClient Uses a client-side cursor supplied
by a local cursor library.
• For backward compatibility, the synonym
adUseClientBatch is also supported
ADO Cursor types
• When your application retrieves rows of data from
SQL Server, it needs a place to store the rowset
while it processes the information.
• An ADO Recordset object encapsulates the data and
the operations allowed on that data. The Recordset
object uses a cursor as a mechanism to organize the
temporary storage.
• The cursor is similar to a dynamic array stored in
memory, and the Recordset object is your interface
to that array.
Within ADO, cursors have three functions

• A) First, the cursor location determines where


to store the rowset while the cursor is open.
• B) Second, the cursor type determines
movement within the cursor and whether the
rowset will reflect users' changes.
• C)Third, the cursor's locking type specifies
how SQL Server will lock the rows on the
server when you want to make changes.
Cursor types
• These cursor types vary in how the cursor
responds to changes in its row membership
and in what directions you can move through
the rowset.
Forward-Only Cursors
• . Forward-only cursors are similar to static
cursors except that forward-only cursors let
you scan only from the first to the last rows in
the cursor. You can update rows, insert new
rows, and delete rows, but you can't move
backward. Only the MoveNext method works
for the forward-only cursor.
adOpenStatic

• Static cursors are so named because additions


and deletions of rows don't change the list of
rows. Furthermore, changes to existing
records don't appear. Any change the cursor
owner makes through the cursor appears
immediately, but the static cursor ignores only
Keyset Cursors
• With keyset cursors, the row membership and
row order are fixed when you open the cursor.
As with a static cursor, your application can
move back and forth between rows. Unlike
static cursors, however, keyset cursors let you
see changes other programs make and
changes your program makes.
Keyset cursors cont’
• Keyset cursors present three special cases.
• First, when a user deletes a row, SQL Server marks the row
as deleted and it becomes inaccessible.
• Second, if a user changes a row so that it no longer
matches the cursor's WHERE clause criteria, SQL Server in
effect removes the row from the cursor as if the user had
deleted it. The row still exists in the table, but it is
inaccessible.
• Third, if another user inserts a row into the table, SQL
Server doesn't add it to the cursor, but if you add a row
through the cursor, it appears at the end of the cursor.
Dynamic Cursors.
• If your application requires immediate access to all
changes, regardless of who makes the changes,
you need to use dynamic cursors. Dynamic cursors
let your application move in any direction through
the cursor, respond immediately to changes in
rowset membership, and show all users' changes
to all rows. Choose dynamic cursors if multiple
users insert, update, and delete rows in the
database at the same time.
Cursor Type (CursorTypeEnum)
adOpenForwar This cursor can be scanned forward only, is
dOnly suitable for one-pass operations. Less expensive
than other types of cursors (default)

adOpenSta A snapshot of the database the moment the cursor


was created. It can be scanned in both directions.
tic You can’t see modifications made by other users
after the creation of the cursor.
adOpenKe Like a dynamic cursor, except that you can't see
records that other users add. Data changes by other
yset users are still visible.

adOpenDyn Additions, changes, and deletions by other users


amic are visible, and all types of movement through the
Recordset are allowed.
Recordset types
• Table Editable. Can locate and return records
quickly because tables are indexable
• Dynasets:Updatable. Efficient because it
represents a set of references to the data in the
underlying query (rather than the actual data).
• Can return records from more than one table
through the use of a join even when those
tables are linked from multiple databases. Such
recordsets are in many cases updatable.
Recordset types
• Snapshot Can be faster than Tables and
Dynasets particularly for smaller recordsets.
Can return records from more than one table
through the use of a join. Such recordsets are
in many cases updatable.
• Unlike Dynasets which return a set of
references to the records in a table a Snapshot
returns a copy of the data which can make
large Snapshots slower than Dynasets
Recordset types
• Forward-Only Faster than but similar to a
Snapshot. Can return records from more than
one table through the use of a join.
• Dynamic Updatable. Can return records from
more than one table through the use of a join.
Particularly well suited to multiuser databases
because they can update themselves when
other users change records contained by
them.
The Connect Property
• The Connect property determines the type of
database to which the Data control is
connected. By default this property is set to
Microsoft Access but you can
• change the setting if you are interested in
connecting to a non-Access data type.
Locking Choices / ADO LOCKING TYPES

• After you choose a cursor type, you need to


choose how ADO will lock a row when you
make a change
Read-Only Locking.
• The read-only locking option doesn't use a lock at
all. This option tells ADO that you won't make any
changes to the rows in the cursor. At most, SQL
Server will place shared locks on the rows as it
reads them and release the locks after it
populates the cursor.
• Because applications don't usually change data
through a cursor, read-only locking is the default
setting.
Pessimistic Locking.
• Pessimistic locking assumes that your changes will
collide with another user’s.
• This option tells ADO to get an exclusive lock on the
row when you make any change to any column in the
record.
• The problem the pessimistic locking option presents is
that the row stays locked until you commit your
changes by calling the Update method. If your update
occurs in the middle of a transaction, then the lock
remains until the transaction ends.
Optimistic Locking.
• To offset the problems of pessimistic locking, ADO offers
the optimistic locking options, Optimistic and
BatchOptimistic.
• These options assume that collisions are unlikely;
therefore, ADO gets the exclusive lock only after you call
the Update or UpdateBatch method. The Optimistic
option lets you work with one row at a time, whereas the
BatchOptimistic option lets you make multiple updates
within the cursor, then save them all at once. When you
call the UpdateBatch method, ADO tries to update each
changed row as a separate, independent update.
• Connecting DAO and adodc using a code
• Set the references approptiately in the
properties window>references.
• Check the libraries for DAO and ADO
Connecting DAO with a code
• Public db As Database
• Public rs As Recordset

• Private Sub Command1_Click()


• rs.addnew
• rs.Fields(0).Value = Text1.Text
• rs.Fields(1).Value = Text2.Text
• rs.Update
• MsgBox ("record saved ")
• End Sub

• Private Sub Form_Load()


• Set db = OpenDatabase("C:\Users\DAIC\OneDrive\Desktop\codes.mdb")
• Set rs = db.openrecordset("select* from stud")
• End Sub
To connect VB6 to MS Access 2003:
• In the General section write the following:
• Dim cn As New ADODB.Connection Dim rs As
New ADODB.Recordset (in Form's Activate Event)
cn.ConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=EMP.mdb;Persist Security Info=False"
cn.Open rs.Open "select Eid,Ename,ppfSub,Basic
From EmpData Order By Eid", cn, adOpenStatic,
adLockPessimistic Text1.text=rs.Fields(0) etc
• In the General section declare the variables for the database
connection and record set object

• Dim cn As ADODB.Connection
• Dim rs As ADODB.Recordset

• Private Sub Form_Load()


• Set cn = New ADODB.Connection
• cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\DAIC\OneDrive\Desktop\codes.mdb;Persist Security
Info=False"
• cn.Open
• Set rs = New ADODB.Recordset
• rs.Open "select*from stud", cn, adOpenKeyset, adLockOptimistic
• Text1.Text = rs.Fields(0)
• Text2.Text = rs.Fields(1)
• End Sub
Add new
• Private Sub Command1_Click()
• rs.AddNew
• rs.Fields(0) = Text1.Text
• rs.Fields(1) = Text2.Text
• rs.Update
• MsgBox ("record saved successfully")
• End Sub

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy