OLEDB an Introduction
Each DBMS stores data in a particular format. For example:
Microsoft Access à MDB
Microsoft FoxPro à DBF
Hence changing from one DBMS to another means rewriting the application to handle data in a new format. This meant that a lot of time and effort is spent in recreating the application.
Open Database Connectivity
The solution to above problem is implemented in Open Database Connectivity (ODBC).
ODBC defines a standard method for communication between application and the DBMS accomplished by defining an Application Programming Interface (API). The ODBC driver accepts the command from the application and converts it to a format understood by the target DBMS.
In addition ODBC drover also receives the result of the command execution from the DBMS and passes it back to the application. OLEDB is a database architecture that enables Application to have uniform access to data stored in diverse information sources, regardless of the location or type.
ActiveX Data Objects (ADO)
ADO is an interface to OLEDB. It enables accessing data from relational and non-relational databases, it allows to access other data sources also.
Accessing Data with ADO Data Control
ADO data control is the key element in creating data applications with a minimum code. It provides visual interface for setting data access properties. It provides link between an application and data, we need to access. We create this by placing ADO data control on a form and setting its properties. Once we establish link we can display data on the form by binding controls to ADO data control without writing code.
ßAdodc Data Control
Connecting to a Data Source
Connection to a data source is created by setting connection string property of ADO data control. This property specifies the type and location of the data base that we need to access.
Ø Use Data Link File
This specifies connection string to connect a data source.
Ø Use ODBC Data Source Name
This allows to use system-defined data source name (DSN) for connection string.
Ø Use Connection String
Specifies a connection string to connect to data source. Clicking Build button displays data link properties dialog box, from which we can specify the Provider Name and other information.
Record Source Property
Specifies where the records will come from after a connection is established to a database. There are four command type options for this property.
Ø adCmdUnknown à Unknown command. This is default value.
Ø adCmdText à Enables to specify SQL command.
Ø adCmdTable à Displays list of tables in connected database.
Ø adCmdStoredProce à Displays list of tables in connected database.
Creating Record Set
Recordset property of ADODC is an object that represents entire set of records from a table or results of an executed command. Recordset object is used to access records returned from a query. At any point of time, Recordset object points to a single record called the current record, in set of records returned from a query. Recordset objects can be used for:-
- Adding Record
AddNew method is used to add new records to a Recordset. While adding new records ADODC clears information in the bound controls to prepare them for addition.
à adoEmployees.Recordset.AddNew
To cancel any changes made to record CancelUpdate method is used.
à adoEmployees.Recordset.CancelUpdate
- Modifying Record
ADODC automatically modifies records when we move to the record that we wish to change.
à adoEmployees.Recordset.Update
- Deleting Record
Delete method enables to delete a record. Record is removed from the database, but the bound controls still display information of the deleted records until we reposition the record pointer to another record.
à adoEmployees.Recordset.Delete
Finding Record
Searching for a specific record requires invoking the Find method of Recordset and specifying condition for the Search.
Syntax:
Object.Find (Critaria, Skiprows, SearchDirection, Start) where
Criteria
Is a string that specifies column name, comparison operator ( >, <= or the LIKE) and value to used in the search.
Skip Rows
Optional, Default value is Zero. It specifies offset from current row or the ‘Start’ parameter to begin Search.
Search Direction
Optional, specifies whether search should begin on current row or next available row in search direction. Its values could be adSearchForward or adSearchBackward.
Start
Optional, specifies starting position. Position for search its values are adBookmarkCurrent for Current Record adBookmarkFirst for First Record and adBookmarkLast for Last Record.
àadoEmployees.Recordset.Find “Emp_Name” = ‘David’”, 0, adSearchBackward, adBookmarkCurrent
Working with ActiveX Data Objects
ADO objects provide us all data access and manipulation features required by most applications. ADO provides minimum number of layers between front-end application and Data Source, to provide high performance interface. It gives a greater control over how an application interacts with data source and enables us to create powerful and flexible applications.
Advantages of ADO Objects
à Validation of any information entered by the user before it goes into database.
à Database applications that don’t require user interface can be created.
à SQL statements can be used to modify multiple records at a time.
ADO object model has following three main objects, that required to access data from an existing database:-
- Connection
Connection object makes a connection between an application and data source as MS SQL Server etc. Creating connection object is similar to setting connection string property an ADODC.
- Record Set
This represents entire set of records from a table or results of an executed command. Recordset object used to access records returned from a query. Data can be entirely manipulated using Recordset objects which is constructed using records (rows) and fields (columns).
- Command
Command object can be used to created Recordset object and obtain records, to execute structure of a database.
Creating and Opening a Connection
By declaring a variable to create a connection string we can create connection object.
à Dim Con as ADODB.Connection
Set Con = New Connection
Creating a Connection Object
By declaring a variable to create a connection string we can create a connection object.
à Dim Con as ADODB.Connection
Set Con = New connection.
ADODB is ProgId (Programmatic Identifier) enables us to create connection object. To create connection object we need to set ConnectionString and ConnectionTimeout properties.
Connection String
Contains information used to establish a connection to a data source. This property supports following arguments:-
Ø Provider
Specifies name of provider used for connection. This property identifies the type of database for connection.
Ø Data source
Specifies name of data source for connection. For Example: Microsoft Access, SQL Server, Oracle etc.
Ø User Id
Specifies Username to be used while opening a connection.
Ø Password
Specifies password to be used while opening a connection.
Parameter Values for different OLEDB provides are:
Microsoft Jet à Microsoft.Jet.OLEDB.3.51 or 4.0
Oracle à MSDAORA
Microsoft ODBC Driver à MSDASQL
SQL Server à SQLOLEDB
Connection TimeOut
This property indicates how long to wait while establishing a connection before terminating the attempt and generating an error.
Example
à Con.ConnectionString = “Provider = Microsoft.Jet.OLEDB.3.51; DataSource = C:\Program Files\Microsoft Visual Studio\VB98\Biblio.mdb”
Con.ConnectionTimeout =30
Opening a Connection
Establish a physical connection to data source using open method. After this method successfully completes the connection still exists and we can issue commands against it and process results.
Syntax:
à Connection.open[Connection String], [UserId],[Password]
Where
Connection String Optional. A string contains connection information.
User Id Optional. User Name is required to establish a connection.
Password Optional. Password required when establishing the connection.
Example1
à Dim Con as ADODB.Connection
Set Con = New Connection
Con.ConnectionString = “Provider = Microsoft.Jet.OLEDB.3.51;”&_
“Data Source = C:\Program Files\ Microsoft Visual Studio\VB98\ Biblio.mdb”
Con.open
Closing the Connection
Close method is used to close the connection object. Closing an object does not remove it from the memory. To completely eliminate an object from memory set object variable to Nothing.
à Con.Close
Set Con = Nothing
Creating and Opening a RecordSet
After connecting to data source, we create Recordset object consisting of the data required from the data source. It can created by using Recordset object itself or by using command object. Recordset can contain a few fields and records from the table or combined information from two or more tables or entire continents of a table.
Recordset is primary means of examining and modifying data in a database. It allows to
Ø Specify which rows are available for manipulation.
Ø Navigate the rows.
Ø Specify order in which rows may be navigated.
Ø Add, Change or Delete rows.
Ø Update data source with changed rows.
The object method is used to create Recordset object with following steps:-
à Declare Recordset object variable
Dim rs as ADODB.Recordset
à Initiate object variable
Set rs = New Recordset
à Use open method to retrieve records from data source.
Syntax:
Recordset.Open [source], [ActiveConnection], [CursorType], [LockType], [Options]
Where
1) Source
Is optional. Variable evaluates to table name or SQL statement. Source depends on the provider we connected to.
2) Active Connection
Optional. If a connection is already created to data source then we can used name of the connection for further communication required to create and maintain the Recordset. If connection has not be established then this parameter supports use of all information required to make a connection.
3) Cursor Type
Optional. Indicates type of cursor the Recordset uses. ADO model supports four types of cursors.
Ø Forward Only
adOpenForwardOnly. Behaves like a dynamic cursor. It allows to scroll only forward through records.
Ø KeySet
adOpenKeyset. Prevents user form seeing records that other users add, and prevents access to records that other users delete.
Ø Dynamic
adOpenDynamic. Allows additions, changes and deletions by other users, and allows all types of movements through the Recordset.
Ø Static
adOpenStatic. Allows all types of movements through Recordset. Additions, changes or deletions by other users will not be visible.
4) LockType
Optional. Indicates types of locks places on records during editing. By default all ADO Recordsets are read-only. Lock types are as follows:
Ø adlockReadOnly Default. Data can not be altered.
Ø adLockPessimistic Provider does what is required to ensure successful editing of the records by “Locking” page containing record immediately upon editing. It prevents other users from editing records.
Ø adLockOptimistic Page containing record is locked while records are updated. Conflict arises when two users attempt to update same record. Update is granted to user who first issues the update method.
Ø adLockBatchOptimistic User Batch update method to write entire batch of rows to the Recordset. Allows to make modifications on a number of rows without having to write those changes to Recordset after each row.
5) Options
Optional. Indicates how provider should evaluate source arguments. Values of this parameter are similar to command type option of record source property of ADODC.
Example: Pessimistic LockType
Dim Con as ADODB.Connection
Dim Rs as New Recordset
Set Con = New Connection
Con.ConnectionString = “Provider=Microsoft.Jet.OLEDB.3.51; Data Source = C:=Program Files\ Microsoft Visual Studio\VB98\Biblio.MDB”
Con.Open
Rs.Open “Select * from Author”,Con.adOpenKeyset, adLockPessimistic
Example : Open Connection in Active Connection parameter of Recordset object.
Dim Rs as New Recordset
Rs.Open “Select * from Author”, &_
“Provider=Microsoft.Jet.OLEDB.3.51; ‘ &_
Data Source = C:=Program Files\ Microsoft Visual Studio\VB98\Biblio.MDB” &_
adOpenKeyset, adLockPessimistic
Displaying data in Recordset
After creating Recordset the fields of each record can be accessed.
à Dim Name as String
à Dim Address as String
Name = Rs.Fields(“C_Name”)
Address = Rs.Fields(“C_Add”)
Above code can also be written with their respective orders, (Field Order).
à Dim Name as String
Dim Address as String
Name = Rs.Fields(0)
Address = Rs.Fields(2)
A short hand method of extracting data by using exclamation point operator (!) called as ‘bang’ can be used to extract data.
à Dim Name as String
Dim Address as String
Name = Rs!C_Name
Address = Rs!C_Add
Following code retrieves information from customer table and places information in the appropriate text boxes.
Example
Private Sub Form_Load ( )
Dim Con As ADODB.Connection
Dim RsCust As ADODB.Recordset
Set Con = New Connection
Con.ConnectionString = “Provider = Microsoft.Jet.OLEDB.3.51; Data Source = C:\Program Files\ Microsoft Visual Studio\VB98\ NWind.MDB”
Con.Open
Set RsCust = New Recordset
RsCust.Open “Customers”, Con
txtCustId.Text = RsCust! CustomerID
txtCustName.Text = RsCust!Customer.Name
End Sub
Navigating through RecordSet
ADO model supports four primary methods of navigating through Recordset object.
Ø MoveNext
Takes user the next record in the Recordset. If an attempt is made to move to the record after EOF, an error occurs.
Ø MovePrevious
Moves user to previous record in the Recordset. Moving past BOF returns in an error.
Ø MoveFirst
Takes the user to the first record.
Ø MoveLast
Takes the user to last record.
Example MovePrevious and MoveFirst Methods
Private Sub CmdPrev_Click ( )
Rs.MovePrevious
If Rs.BOF = True Then
MsgBox “Already at the beginning of the Recordset”
Rs.MoveFirst
End If
End Sub
Finding Records
User can search a Recordset for record that satisfies a condition. If a condition is met, Recordset position is set on the found Record; otherwise position is set on end of the Recordset using find method.
Syntax:
Object.Find(Criteria, Skiprows, SearchDirection, Start)
RsCust.Find “Age>40”, 0, adSearchForward, adBookmarkCurrent
Editing Records
User can make changes and save results back to data source.
Syntax:
Recordset.Update Fields, values where:
Fields Optional, Represents a name of the field/ fields to modify.
Values Optional, represents values in the field of new record.
Private Sub CmdSave_Click ( )
RsPub!Name = txtName.Text
RsPub!City = txtCity.Text
RsPub.Update
End Sub
Adding Records
AddNew method is used to insert new record. This method is invoked prior to inserting values. Once required values are inserted the values are saved back to data source using update method. Newly inserted records are added at the end of Recordset.
Private Sub Add ( )
If(TxtId.Text < > “”) And (TxtName.Text<> “” )Then
rsTemp.AddNew
rsTemp.Emp_Id = txtId.Text
rsTemp. = txtName.Text
rsTemp.Update
End If
End Sub
Deleting Records
Delete method deletes current record from a Recordset, only one record at a time can be deleted from the database.After deleting current record, it is deleted from database, but deleted records remains current until we move to different record.
Private Sub CmdDelete_Click ( )
Dim Ans as Integer
Ans = MsgBox(“Want to Delete Record?”,vbYesNo)
If Ans = vbyes then
rsEmp.Delete
rsEmp.MoveFirst
Else
Exit Sub
End If
End Sub
Closing Recordset
Close method is used to close a Recordset and free system resources.
Syntax:
à Recordset.Close
Using Command Object
Using command object SQL command can be executed to retrieve data. Properties and methods of command object are:-
- Active Connection Property
References a connection for command execution.
- Command Text Property
Contains text of a command that you want to issue against a provider.
- Command Type Property
Indicates type of a command object. This could be adCmdText, adCmdUnknown, adCmdTable, adCmdStoredProc. This is similar to option parameter of the open method.
- Create Parameter Method
Adds parameter to parameters collection of command object.
- Execute Method
Executes command object.
Syntax:
à Commandobject.Parameters.Append.object
à Command.CreateParameter (Name, Type, Direction, Size, Value ) Where
Name String specifying name of the parameter object.
Type Specifies data type of parameter object.
Direction Specifies whether data is to be sent to a query or returned from query.
Size Specifies maximum length of the parameter value in character or bytes.
Value Specifies value of parameter object.
Following code update student name in student table:-
Private Sub Form_Load ( )
Dim Con as ADODB.Connection
Dim Cmd as ADODB.Command
Dim Str as String
Set Con = New ADODB.Connection
Set Cmd = New ADODB.Command
Con.ConnectionString = “Provider = Microsoft.Jet.OLEDB.3.51; Data Source = C:\ Program Files \ Microsoft Visual Studio\VB98\StudentData.mdb”
Con.Open
Set Cmd.ActiveConnection =Con
Str = “Update Student Set StudentName = “Jim Waugh’ where StudentName = ‘Lis Nizan’”
cmd.CommandText =Str
Cmd.Execute
End Sub
Collections
Collection is way of grouping a set of related items. It keeps track of loaded forms in a program or controls of a form.
Collections have their own properties and methods. Objects in a collection are referred to a ‘Members’ of the collection i.e. numbered sequentially beginning from 0. This is the ‘index number’ of the member. Collections have following features:-
1) We can add items to collection.
2) We can remove items from a collection.
3) We can refer to specific members of collection.
4) Collection object keeps a count of number of members in a collection.
Private Sub CmdSave_Click( )
Dim Ctrl as Control
For each Ctrl in Controls
If type of Ctrl is TextBox Then
If Ctrl.Text = “” Then
MsgBox “All fiels must be entered”
Exit Sub
End If
End If
Next Ctrl
End Sub
Methods of collection are:-
Ø Add Method Used to Add members to a collection.
Syntax:
Object.AddItem, Key, before, after
Where
Item Is the member to be added to collection.
Key Is a String used to identify the member
Before Specifies New Item should be placed in collection before member specified in Before parameter.
After Specifies that new item should be placed in a collection after member specified in After parameter.
à Col.Add inst, “Mkey”
Ø Remove Method
Used to remove items from collection just as we can add items to the collection.
Syntax:
à Object.Remove(index)
Index can be either numeric index of the member of the key property of the member.
à Coll.Remove3 OR
à Coll.Remove “E003”
Ø Item Method
Used to access specific item from collection.
Syntax:
à object.item(index)
Index can be either numeric of the member or its key property.
à Col.Item(3) OR
à Col.Item(“E003”)
Count Property
Collection has Single property and is used to tell how many items are there in the collection.
Syntax:
à Object.Count
Count Property in Code is as follows:
Dim I as Integer
For I =1 to Col.(Count)
Print Col.Item (I)
Next I