enterprise development using visual basic 6.0 autumn 2002 tirgul #9

90
‘Tirgul’ # 9 Enterprise Enterprise Development Development Using Visual Basic Using Visual Basic 6.0 6.0 Autumn 2002 Autumn 2002 Tirgul #9 Tirgul #9

Upload: arav

Post on 19-Jan-2016

42 views

Category:

Documents


0 download

DESCRIPTION

Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #9. Objectives. Understanding ADO Using DSN/DSN’less connection In-depth: Connection RecordSet Command. 3-Tier Architecture. The Data Access Layer. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ # 9

Enterprise Enterprise Development Development

Using Visual Basic 6.0 Using Visual Basic 6.0 Autumn 2002Autumn 2002

Tirgul #9Tirgul #9

Page 2: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

ObjectivesObjectives

• Understanding ADO

• Using DSN/DSN’less connection

• In-depth:

– Connection

– RecordSet

– Command

Page 3: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

3-Tier Architecture3-Tier Architecture

Page 4: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

The Data Access LayerThe Data Access Layer

• Almost any enterprise application have some needs to access data (database, web, email, legacy data..)

• Microsoft has developed a technology to make this task simple for us

• VB makes it easy to use

Page 5: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

The ProblemThe Problem• Each data source has different way to

access it

SQL Data•SQL Server•Oracle•Informix•DB2•Fox Pro•Jet

Non SQL Data•Mail•Video•Text•Web•...

Mainframe and Legacy Data

Page 6: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

The SolutionThe Solution

• Single high level,efficient programming, paradigm to work with everything it is called:

universal data access (UDA)

• The programmer can use the same code to access any data!

Page 7: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

What is UDA?What is UDA?

• UDO Consist of:

– ActiveX Data Objects(ADO)

– OLE DB

– And other…

Together these interfaces provide us the means to work with any data

Page 8: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

UDA ArchitectureUDA Architecture

0

Data ProvidersData Providers

Mainframe and Legacy Data

SQL Data•SQL Server•Oracle•Fox Pro•Jet

Non SQL Data•Mail•Video•Text•Web

OLE DB

Data consumerData consumer

ADO

Application (VB, VC++,ASP)

Page 9: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

What is ADO?What is ADO?• ADO is one of the components of the UDA model.• Other components:

– Remote Data Services (RDS)– OLE DB is Microsoft's component database architecture that provides

universal data integration over an enterprise's network— from mainframe to desktop - regardless of the data type

– Open Database Connectivity (ODBC) provide a unified way to access relational data as part of the OLE DB specification

Page 10: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

ADO LayerADO Layer

Page 11: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Ado Object Model Ado Object Model OverviewOverview

• High level, language independent, data access interface

• Provides layer to the underplaying data source (OLE DB Provider)

• Object Oriented interface for accessing data• ADO is small, lightweight, fast, and feature

complete – everything you need when you are programming either for the database applications or the Internet

Page 12: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

ADO ObjectsADO Objects

• object-based interface that provides a logical set of objects you can access from code

Object Functionality

Connection

Manages the connection with the data source

Command Defines the commands that will be executed against the data source

Recordset Contains the data that is retrieved from the data source

Page 13: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

ADO ObjectsADO Objects

• ADO objects are not dependant on one another. you can create instances of objects independently of one another, for example, you can create a Recordset object without creating a connection object.

• Unlike the older technologies, ADO is more flexible, ADO code is easier to write, read and maintain.

• ADO is built on top of OLE DB and is capable of accessing any sort of data that is wrapped and exposed by an appropriate OLE DB provider.

Page 14: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Basic ADO operationsBasic ADO operations

• Select Query

• Update Query

• Delete Query

• Integrity Constraints (PK/FK)

• Transactions (Begin, Commit, Rollback)

• Stored Procedures

Page 15: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

ADO ObjectsADO Objects

• Connection• Recordset• Command• Parameter• Error• Field• Property• Stream

Page 16: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

The Connection ObjectThe Connection Object

• The connection object enable us to connect to data stores.

• In this object we specify which:– OLE DB provider we wish to use.– Security details for the connection.– And other specific details.

• NOTE: in some cases you do not have to define a connection object. Then ADO will create one for you. as a rule, always define connection object explicitly.

Page 17: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

The Command ObjectThe Command Object

• The command object is designed for running command against a data store

• You may also execute command using the connection object but these command have restrictions.

Page 18: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

The Recordset ObjectThe Recordset Object

• The most commonly used object.• It contains a set of data we extract from the data

stores.• The Recordset holds the record that are usually

fetched from a query• It allows us to:

– Change the data (update, delete, add).– Iterate the records.– Filter the record so that only a subset is shown.

• A Recordset also has a fields collection where there is a filed object for each column in the Recordset

Page 19: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

DISPLAYING DATA WITH A RECORDSET (USING A DISPLAYING DATA WITH A RECORDSET (USING A CONNECTION OBJECT)CONNECTION OBJECT)

Set Con = new ADODB.ConnectionSet RS = new ADODB.RecordsetCon.open “DSN=myDB;UID=sa;Password=;”RS.ActiceConnection = Con RS.open “select * from Users”while not RS.EOF   msgBox RS.fields(“fname”).values

RS.MoveNext

Wend

RS.CloseCon.Close

Page 20: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

DISPLAYING DATA WITH A RECORDSET (USING A DISPLAYING DATA WITH A RECORDSET (USING A CONNECTION OBJECT 2)CONNECTION OBJECT 2)

StrConnect = “DSN=myDB;UID=sa;Password=;”Set Con = new ADODB.ConnectionCon.open “DSN=myDB;UID=sa;Password=;”Set RS =new ADODB.RecordsetRS.Open “select * from Users”, Con,adopenkeyset,adlockoptimisticwhile not objRec.EOF   msgBox RS.fields(“fname”).values   RS.MoveNext

WendRS.Close

Page 21: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

DISPLAYING DATA WITH A RECORDSET (WITHOUT  A DISPLAYING DATA WITH A RECORDSET (WITHOUT  A CONNECTION OBJECT)CONNECTION OBJECT)

StrConnect = “DSN=myDB;UID=sa;Password=;”

Set RS =new ADODB.Recordset

RS.Open “select * from Users”,strConnect,

adopenkeyset, adlockoptimistic

while not objRec.EOF

   msgBox RS.fields(“fname”).values

  RS.MoveNext

Wend

RS.Close

Page 22: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

ADO 2.5 ExtensionsADO 2.5 Extensions

• Record Object

• Stream Object

• Not in this course scope

• Mainly for handling non relation data such as File System, Email System XML Files..

Page 23: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

ADO CollectionsADO Collections

• There are several collections in the ADO object library.– Fields collection.

• This collection is a member of the Recordset object.

• Each member of the collection is filed object.• In SQL structured data the field correspond to a

column and contains information about the column:

– Name, data type, length..

Page 24: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

ADO Collections – Cont.ADO Collections – Cont.

• There several other collections:

– Parameter – part of the command object

– Errors – part of the connection object

– Properties

Page 25: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Connecting to Data SourceConnecting to Data Source

• In order to access some data source, you have to connect to it using the connection object.

• The actual method of connecting to the data store is the same for all stores.

• The actual details may be different between different providers

• There are several ways to connect to data source:– Using a connection string – DSN’less– Using ODBC data source – DSN– Using data link file

Page 26: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

DSNDSN

• DSN = 'Data Source Name'

• DSN is an easy way to assign useful and meaningful names to data sources which may not be limited to databases alone (e.g Excel spread sheet etc.)

Page 27: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Creating a DSN (1)Creating a DSN (1)

• Database exists

• ODBC32 exists (Check control panel)

– Go into Control Panel

– NT ONLY - Go into Administration Tools

– Look for ODBC Data Sources (32-bit) or Data Sources (ODBC)

Page 28: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Creating a DSN (2)Creating a DSN (2)

• Go into Control Panel

• Then Administrative Tools

Page 29: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Creating a DSN (3)Creating a DSN (3)

• Then ODBC Data Sources (or some sort of ODBC)

Page 30: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Creating a DSN (4)Creating a DSN (4)

• Then click on the System DSN tab and click on add

User DSN - DSN's for you only.

System DSN - The whole system can see these

they are ones that everyone that accesses your computer can see.

Page 31: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Creating a DSN (5)Creating a DSN (5)

• Choose your driver

Page 32: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Creating a DSN (6)Creating a DSN (6)

• Set up the DSN

Enter a Data Source Name, this is what we call your Database, so keep it short and without spaces. eg. myBooks

Click on Select... to browse to the directory where your database is and choose it, this tells ODBC where you find the DB (well duh!)

If you set a password for your database click on Advanced...

Page 33: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Creating a DSN (7)Creating a DSN (7)

• Passwords?

Access only supports passwords, not usernames, so just enter the password and click OK.

Click OK to the other dialog and you can see your DSN listed in the System DSN list, now you can use it to set up databases.

Page 34: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

CCreate thereate the Northwind DSN Northwind DSN

• Northwind is a sample Access DB.

• It comes with Microsoft office installation.

• Use ‘Search’..

Page 35: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Add Add Northwind DSNNorthwind DSN– Select Access – Select Access Driver Driver

Select Access Driver

Page 36: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Add Northwind DSN – Select Data Add Northwind DSN – Select Data basebase

Use Select to select database

Page 37: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Add Northwind DSN – Browse for Add Northwind DSN – Browse for NorthwindNorthwind

Page 38: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Add Northwind DSN – Set name and Add Northwind DSN – Set name and descriptiondescription

Page 39: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Add Northwind DSN – Done, new in the listAdd Northwind DSN – Done, new in the list

Northwind added

Page 40: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

DSN vs DSN less Database DSN vs DSN less Database Connections Connections

• you can connect to DSN using following code:

Dim con as new ADODB.Connection

con.Open "DSN=myDSN"

…Use Connection

con.Close

Set con = Nothing

Dim con as new ADODB.Connection

con.Open "DSN=myDSN"

…Use Connection

con.Close

Set con = Nothing

DSN Name only

Other data is hidden in the DSN itself

Page 41: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

DSN’less ConnectionDSN’less Connection

• DSN’less connection does not require creation of system level DSNs for connecting to databases and provide an alternative to DSNs.

• We will now see how to connect to a database using Connection String in place of DSN name.

Page 42: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

DSN less Connection StringDSN less Connection String

Dim con as new ADODB.Connection

con.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data“ & _ "Source=c:\path\to\database.mdb"

…Use Connection

con.Close

Set con = Nothing

Dim con as new ADODB.Connection

con.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data“ & _ "Source=c:\path\to\database.mdb"

…Use Connection

con.Close

Set con = Nothing

All Connection Data

Page 43: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Why to use DSN Connections ?Why to use DSN Connections ?

• Provides meaningful data source names.

• When there are lots of data sources to think of and you want a central repository to hold a collection of data sources without having to worrying about the actual configuration of the data source.

Page 44: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Why to use DSN less Why to use DSN less Connections ?Connections ?

• When you can't register DSNs yourself e.g. when you are running a virtual hosting account on other's server. Stop emailing system administrator, connect to your databases directly.

• Provides faster database access because it uses native OLE DB providers which provide faster database connection.

Page 45: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

ADO Connection StringADO Connection String

• For MS Access database:Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\some-folder\mydatabase.mdb; User ID=admin; Password=;

• For MS SQL Server:Provider=SQLOLEDB; Data Source=server_name_or_address; Initial Catalog=database_name; User ID=username; Password=password; Network Library=dbmssocn;

Page 46: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Building a Connection StringBuilding a Connection String

• Create a UDL file– Right click on Desktop,

New -> Text File, rename to filename.UDL

• Double-click the UDL file• Select Microsoft.Jet.OLEDB.4.0

Page 47: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Building a Connection String Building a Connection String (cont.)(cont.)

• Click Next >>

• Browse for the Accessdatabase

• Enter login informationif necessary

Page 48: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

• Click OK

• Open the UDL file using Notepad

Building a Connection String Building a Connection String (cont.)(cont.)

Page 49: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Connection – Open MethodConnection – Open Method

• The connection object has an open method:– Connection.Open [connetionstring], [user id], [password], [options]

ConnectionString The String containing the connection details

UserID The name of the user during the connection. Overides the user name in the connection string

Password Same as user but password

Options adAsyncConnect or empty

Page 50: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Establishing a SQL Database Establishing a SQL Database Connection Connection

Set a reference to the ADO object library

To set a reference to the ADO Library in VB, click the Project menu, and click Reference. Then select the appropriate reference

Declare a Connection Object

Dim conn as ADODB.ConnectionSet conn = new ADODB.Connection

Specify an OLE DB Data Provider

Conn.Provider = “SQLOLEDB”

Specify Connection Information

Use the connection string property to specify any additional information

strCnn = "Data Source=ds;uid=sa;pwd=;” & _

database=pubs;Initial Catalog=pubs"

Open a connection Use the open method to establish connection to the data sourceconn.open strCnn

Page 51: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Opening a ConnectionOpening a Connection

Page 52: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Closing a ConnectionClosing a Connection

• When you finished working with the data source, use close method of the connection object. – Free any associated system resources– Close any active Recordset associates with this connection– Set the object to nothing in order to move the object from

memoryConn.CloseSet Conn = nothing– NOTE: connection will be closed automatically when the

connection variable goes out of scope or set to nothing– Closing connection is very important for scalability and

performance especially when it is being used over the web (connection pooling)

Page 53: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

The Connection Object - The Connection Object - InterfaceInterface

• Properties

– CommandTimeout

– ConnectionString

– ConnectionTimeout

– CursorLocation

– DefaultDatabase

– IsolationLevel

– Mode

– Provider

– State

– Version

• Methods

– BeginTrans

– Close

– CommitTrans

– Execute

– Open

– OpenSchema

– RollbackTrans

• Collections

– Errors

– Properties

Page 54: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

RecordsetsRecordsets

• Recordset contains the data as a table.

• Knowing the details of how the data is held is and manipulated is essential.

• It allows you to make informed decision of what type of Recordset you are going to use.

Page 55: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Recordset & CursorsRecordset & Cursors

• Like every other object a Recordset has data, methods and state.

• Each Recordset set has one pointer to the current record.

• The curser is what manage the set of records and the current location within the record

• When you iterate through records, the cursor performs the move. When you try to move beyond the last record the curser handles it.

Page 56: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Recordset & CursorsRecordset & Cursors

ID Name Phone

111111 Bob 555555

222222 Mary 666666

333333 Bil 777777

Cursor Engine

Current Record

Page 57: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Cursors TypeCursors Type• Static (adOpenStatic).

– Contains a static copy of the record– The content of the Recordset are at the time the record

is being created.– Any record modified, added or deleted by other user

will not be visible.– Movement through the Recordset is allowed both

forward and backward• Forward only (adOpenForward)

– The default cursor type– Identical to static except you can only move forward

through the Recordset

Page 58: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Cursor Types – Cont.Cursor Types – Cont.

• Dynamic (adOpenDynamic). – Doesn’t have fixed set of records– Any changes by other users will be visible in the

Recordset– Movement is allowed in both directions

• Keyset (adOpenKeyset).– Like dynamics, any changes are visible except

new records.– If other user delete a record this record will be

inaccessible by the Recordset

Page 59: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Performance issuePerformance issue

• Why are static cursor are slower the forward –only cursor?– Forward cursor do no have to keep any

track about records they past, static do!• If you just want to look at the records in order

to build a table, what kind of cursor would you be using?– Forward only

Page 60: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Recordset and LocksRecordset and Locks

• Before getting into recordset creation and manipulation. There is another last topic – Locks

• Locking is a mechanism to ensure Integrity of the data, making sure that changes aren’t overwritten

• We want to make sure that my changes of the data will be overwritten by other user changes

• To manage this protection we use locking.• There are several type of recordset locks

Page 61: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Lock typesLock types

• Lock Types:– Read Only (adLockReadOnly) – The default

locking type. Recordset is read only.– Pessimistic (adLockPessimistic) – Locking a

record whenever editing is taking place– Optimistic (adLockOptmistic) – The record is

not locked until changes to the data are committed to the data store

– Batch Optimistic (adLockBatchOptimistic). Allows multiple records to be modified, and the records are only locked when the UpdateBatch method is called

Page 62: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Performance issuePerformance issue

• If you do not need to modify records what locking would you be using?– Read-only

• Pessimistic insures more integrity, why not use it always?– Concurrency, a locked records is

available to other user therefore concurrency is reduced

Page 63: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Creating a RecordsetCreating a Recordset• Creating Recordset is achieved by using the open

method• Recordset.Open [source] , [ActiveConnection] , [CursorType] ,

[LockType], [options]

Source The source of the data. Can be the name of the table is the database, an SQL string, a stored procuder or a command object

ActiveConnection The connection to use for this connection. Can be an open Connection object or a connection string

CursorType The type of cursor to use. The default is adForwardOnly

LockType The type of locking to use. The default is adLockReadOnly

Options Tells the provider what the source argument is – that is, whether is is a table, a text string and so on

Page 64: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Creating RecordsetCreating Recordset

An opened connection object

Page 65: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

The Recordset ObjectThe Recordset Object• Properties

• AbsolutePage, AbsolutePosition, ActiveConnection, BOF, Bookmark, CacheSize, CursorLocation, CursorType, EditMode, EOF, Filter, LockType, MarshalOptions, MaxRecords, PageCount, PageSize, RecordCount, Source, State, Status

• Methods

– AddNew, CancelBatch, CancelUpdate, Clone, Close, Delete, GetRows, Move, MoveFirst, MoveLast, MoveNext, MovePrevious, NextRecordset, Open, Requery, Resync, Supports, Update, UpdateBatch

• Collections

– Fields, Properties

Page 66: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Navigating Through Navigating Through RecordsRecords

• Once you opened a record you often need to loop through each record

• If your Recordset allow moving backwards you can use MovePrevious and check the BOF property

• There are also MoveFirst , MoveLast and Move methods

rsAuthors.Open “authors” , connDo While Not rsAuthors.EOF

Debug.Print rsAuthors(“au_lname”) & “,” & _ rsAuthors(“au_fname”) rsAuthors.MoveNext

Loop

rsAuthors.Open “authors” , connDo While Not rsAuthors.EOF

Debug.Print rsAuthors(“au_lname”) & “,” & _ rsAuthors(“au_fname”) rsAuthors.MoveNext

Loop

EOF property is true when the end of the Recordset has been reached

EOF property is true when the end of the Recordset has been reached

Page 67: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Using the Fields CollectionUsing the Fields Collection

• The fields collection contains a field for each column in the Recordset.

• The fields collection is the default collection and therefore can be omitted when accessing fields.

• The following example all return the same result.

Page 68: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Using the Fields CollectionUsing the Fields Collection

rsAuthors.Fileds(“au_lname”).Value

rsAuthors(“au_lname).Value

rsAuthors(1).Value

rsAuthors.Fields(1).Value

rsAuthors(“ay_lname”)

rsAuthors(1)

rsAuthors.Fileds(“au_lname”).Value

rsAuthors(“au_lname).Value

rsAuthors(1).Value

rsAuthors.Fields(1).Value

rsAuthors(“ay_lname”)

rsAuthors(1)

Default collection

Default collection & Property

Don’t forget to use Trim when add/Select a String

Page 69: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Using the Fields CollectionUsing the Fields CollectionTo Get Meta DataTo Get Meta Data

Page 70: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

BookmarksBookmarks• When you are moving around the Recordset you might want to

retain the position of a record and then move back to it later• A Recordset move bookmark holds a unique pointer to an

individual record• To Bookmark you simple assign the bookmark property to a

variable

• To return to the bookmark position you do the opposite

Dim varBkMark as VariantvarBkMark = rsAuthors.BookMarkDim varBkMark as VariantvarBkMark = rsAuthors.BookMark

rsAuthors.BookMark = varBkMark rsAuthors.BookMark = varBkMark

NOTE: Not all records support Bookmarks. The support method allows you to identify that

If rsAuthors.Support(adBookmark) then…

Page 71: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Filtering RecordsetsFiltering Recordsets

• Filtering is a way to temporarily restricting the view of records in a Recordset

• It is useful if you want to show subset of records without re-queering the data store

rsAuthors.Filter = “State=‘ca’”rsAuthors.Filter = “au_lname = ‘homer’ or au_lname = ‘Francis’”rsAuthors.Filter = “au_lname LIKE ‘Ho%’”rsAuthors.Filter = “” ‘Reset filtering

rsAuthors.Filter = “State=‘ca’”rsAuthors.Filter = “au_lname = ‘homer’ or au_lname = ‘Francis’”rsAuthors.Filter = “au_lname LIKE ‘Ho%’”rsAuthors.Filter = “” ‘Reset filtering

Page 72: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Filtering With ConstantsFiltering With Constants

• The filter property can also take one of the FilterGroupEnum constants as its argument. These are:– adFilterNone – removes current filter– adFilterpendingRecords – to view

only records that have changed but not yet been sent to server (batch update move)

• Look in the MSDN for the other constants

Page 73: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Filtering with BookmarksFiltering with Bookmarks

The filter is applied on the bookmarks array

The Array function must be used to convert the individual bookmark to a variant array

Page 74: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Searching for RecordSearching for Record• Searching for individual records is performed using the find method

• You can only have one criterion – And or Or is not allowed• You can use optional argument to specify extra options

• If record is found you are placed at that record• Else you are either at EOF or BOF depending on the search direction

rsAuthors.Find = “au_lname = ‘loyd’”rsAuthors.Find = “au_lname = ‘loyd’”

Recordset.Find = Criteria , [SkipRow], [SearchDirection],[Start]Recordset.Find = Criteria , [SkipRow], [SearchDirection],[Start]

SkipRow Number of rows to skip before search (0 by default)

SearchDirection Can be either adSearchForward or adSearchBackWard

Start Start is a Bookmark identifing where to start from

Page 75: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Searching for Record – Using Searching for Record – Using BookmarkBookmark

‘ Save current positionvarBkmk = rsAuthors.BookMark

‘Find the RecordrsAuthors.Find “au_lname = ‘Sussman’”

‘Was it foundIf Not rsAuthors.EOF then

Debug.write “Found: “ & rsAuthors(“au_lname”)Else

Debug.write “Not Found. Moving”rsAuthors.Bookmark = varBkmk

End If

‘ Save current positionvarBkmk = rsAuthors.BookMark

‘Find the RecordrsAuthors.Find “au_lname = ‘Sussman’”

‘Was it foundIf Not rsAuthors.EOF then

Debug.write “Found: “ & rsAuthors(“au_lname”)Else

Debug.write “Not Found. Moving”rsAuthors.Bookmark = varBkmk

End If

Page 76: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Modifying RecordsModifying Records

• Up to now we saw methods and properties to query the Recordset.

• However many times we want to modify records:– Using: Add, delete, update..

• Modifying records can be done both using the Connection, Command and Recordset objects.

• Each method has advantages and disadvantages.

To modify a record in recordset you must have locking type other than AdLockReadOnly – remember this is the default.

Page 77: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Adding Records using Adding Records using RecordsetRecordset

• There are two ways to add records, both use the AddNew method:

With rsAuthors.Open “authors”, conn, adOpenDynamic, _

adLockOpimistic, adCmdTableDirect.AddNew Array(“ui_id” , “au_lname” , “au_fname” , “Contract”), _ Array(“123-12-1234”, “Lloyd”, “Janine”, 0)

End With

With rsAuthors.Open “authors”, conn, adOpenDynamic, _

adLockOpimistic, adCmdTableDirect.AddNew Array(“ui_id” , “au_lname” , “au_fname” , “Contract”), _ Array(“123-12-1234”, “Lloyd”, “Janine”, 0)

End With

With rsAuthors.Open “authors”, conn, adOpenDynamic, _

adLockOpimistic, adCmdTableDirect.AddNew

.Fields(“ui_id”) = “123-12-1234”

.Fields(“au_lname”) = “Lloyd”

.Fields(“au_fname”) = “Janine”

.Fields(“Contract”) = 0.Update

End with

With rsAuthors.Open “authors”, conn, adOpenDynamic, _

adLockOpimistic, adCmdTableDirect.AddNew

.Fields(“ui_id”) = “123-12-1234”

.Fields(“au_lname”) = “Lloyd”

.Fields(“au_fname”) = “Janine”

.Fields(“Contract”) = 0.Update

End with

Requires the Update method

Page 78: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Editing Records using Editing Records using RecordsetRecordset

• Editing records is similar to the first method of inserting records- the difference being that you don’t need to call the AddNew method

strSQL = “SELECT * FROM authors WHERE au_lname = ‘Lloyd’”With rsAuthors

.Open strSQL , conn, adOpenDynamic, _ adLockOpimistic, adCmdTableDirect

.Fields(“Contract”) = 1

.UpdateEnd with

strSQL = “SELECT * FROM authors WHERE au_lname = ‘Lloyd’”With rsAuthors

.Open strSQL , conn, adOpenDynamic, _ adLockOpimistic, adCmdTableDirect

.Fields(“Contract”) = 1

.UpdateEnd with

The example above simply set the “contract” field of the current record (in this case the first record) to 1

Page 79: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Deleting Records using Deleting Records using RecordsetRecordset

• To Delete records you call the Delete method. You may add optional argument from the Affect Enum constants– adAffectCurrent – delete the current record

(default)– adAffectGroup – all records matching the

current filter will be deleted– adAffectAll – all records in the recordset will

be deleted

rsAuthors.DeletersAuthors.Delete Deletes the current record

Page 80: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Operations using ConnectionOperations using Connection

• All operations (Select/Add/Edit/Delete) could be executed using the Connection object:

• For Select (Returned Recordset)

• For Add/Edit/Delete(No need for Recordset)

Dim Conn As New ADODB.Connection

Dim RS As ADODB.Recordset

Set RS = Conn.Execute(SQLCommand, RecordsAffected)

Dim Conn As New ADODB.Connection

Conn.Execute SQLCommand, RecordsAffected

SQL command

Page 81: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Operations using CommendOperations using Commend• All operations (Select/Add/Edit/Delete) could be

executed using the Command object.• For a row-returning Command:

• For a non–row-returning Command:

Dim Command As New ADODB.Command

Dim RS as new ADODB.RecordSet

Set RS = Command.Execute( RecordsAffected, Parameters, Options )

Dim Command As New ADODB.Command

Command.Execute RecordsAffected, Parameters, Options

Page 82: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Working with CommandWorking with Command

• Assume we have an open connection:

Dim Command As New ADODB.Command

Set Command.ActiveConnection = Conn

Command.CommandText = strSQLCommand

Command.Execute

Page 83: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Working with Command Working with Command parameterparameter

Dim adoCn As ADODB.Connection Dim adoCmd As ADODB.Command Dim adoParam As ADODB.Parameter Set adoCmd = New ADODB.Command With adoCmd

.CommandType = adCmdStoredProc

.CommandText = “SP_Cart_DeleteAll" '***Build parameters collection Set adoParam = .CreateParameter(Name:="RETURN_VALUE", Type:=adInteger,Direction:=adParamReturnValue) .Parameters.Append adoParam Set adoParam = .CreateParameter(Name:="@SessionID", Type:=adInteger, Size:=4,Direction:=adParamInput, Value:=SessionID) .Parameters.Append adoParam

End With adoCmd.ActiveConnection = GetConnection()adoCmd.Execute  

• Common for stored procedures

Page 84: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Working with Command Working with Command parameterparameter

Dim Command As New ADODB.Command

Dim param as ADODB.Parameter

Set Command.ActiveConnection = Conn

Command.CommandText = GET_STUDENT_DATA_QUERY

Command.CommandType = adCmdText

Set param = MyCommand.CreateParameter(, adVarChar, adParamInputOutput, 50)

param.value = “1”

Command.Parameters.Append param

Command.Execute

Public Const GET_STUDENT_DATA_QUERY = “Select * from Students where StudentID = ?” Dynamic

variable

Page 85: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Auto Increment Field Auto Increment Field ProblemProblem

• Assume you have a table “tblTest” containing two files – ID – auto incremented integer – Name – text

• What will the following code produce?

• Seems trivial but whether you can obtain this value after adding a new record depends upon the cursor type, lock type, and whether ID is indexed or not.

With rsData.Open “tblTest” , conn, adOpenDynamic, _

adLockOpimistic, adCmdTableDirect.AddNew .Fields(“Name”) = “Janine”.UpdateDebug.Print .Fields(“ID”)

End with

With rsData.Open “tblTest” , conn, adOpenDynamic, _

adLockOpimistic, adCmdTableDirect.AddNew .Fields(“Name”) = “Janine”.UpdateDebug.Print .Fields(“ID”)

End with

Page 86: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Auto Increment Field Auto Increment Field ProblemProblem

• Any of the following combinations will return the new value

Provider Target Indexed CursorLocation

Cursor Type

LockType

Jet 4.0 Access97 Yes Server All All

Access2000 Yes Server All All

No Client All PessimisticOptimistic

SQL OLE DB

SQL Server 7.0 Yes Server keySet PessimisticOptimistic

Client All PessimisticOptimistic

No Client All PessimisticOptimistic

Page 87: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

Managing ErrorsManaging Errors

• When dealing with data store many run time errors may arise :– Security problems.– Synchronization – updating deleted

record.– Connection – network..

• You can’t guarantee that every think is going to work perfectly.

Page 88: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

The Errors CollectionThe Errors Collection

• The errors collection contains an error object for each error that accurred during a single ADO command.

• The OLE DB provider set this objects.• Two important points to remember.

– Each time an ADO command is executed, if an error occurs , the collection is cleared and filled. If no error occurs than the collection is untouched.

– The OLE DB provider may fill the error collection with information and warning messages. These always have error number 0.

Page 89: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

The Errors CollectionThe Errors Collection• The collection is part of the connection

object

– Connection.Errors

• You can also access the collection from the Recordset object

– rsAuthors.ActiveConnection.ErrorsFor Each errAuthors in rsAuthors.ActiveConnection.Errors

‘Handle/Display ErrorNext

For Each errAuthors in rsAuthors.ActiveConnection.Errors‘Handle/Display Error

Next

Page 90: Enterprise Development  Using Visual Basic 6.0   Autumn 2002 Tirgul #9

‘Tirgul’ #9

The Error ObjectThe Error Object

• Each member of the errors collection is an error type

Property Description

Number The ADO Error number

NativeError The error number from the data provider

SQLState The 5 digit SQL state code for the error, when connecting to an SQL database

Source The Object that generated the error

Description Descriptive text of the error