database access using ado-i

Upload: gautam-thombre

Post on 02-Apr-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 Database Access Using ADO-I

    1/73

    29-Jul-02 Information Technology for

    Mana ement

    1

    Database Access using ADO I(ADO Data Control &

    Data Bound Control)

    Vivek Gupta

    IT & Systems Group

    Indian Institute of ManagementLucknow

    Doing the best at this moment puts you in the best

    place for the next moment

    -- Oprah Winfrey

  • 7/27/2019 Database Access Using ADO-I

    2/73

    29-Jul-02 Information Technology for

    Mana ement

    2

    One

    ADO Data Control

  • 7/27/2019 Database Access Using ADO-I

    3/73

    29-Jul-02 Information Technology for

    Mana ement

    3

    ADO Data Control The ADO (ActiveX Data Object) data control is the

    primary interface between a Visual Basic applicationand a database.

    It can be used without writing any code at all! Or, It can be a central part of a complex database

    management system.

    The ADO data control does not appear in the standardVisual Basic toolbox - it must be added.

    Select Project from the main menu, then clickComponents. The Components window will appear.Select Microsoft ADO Data Control, then click OK. Thecontrol will be added to your toolbox.

    The data control (or tool) can access databases created byother programs besides Visual Basic (or MS Access).

    Some other formats supported include dBase, FoxPro,and Paradox.

  • 7/27/2019 Database Access Using ADO-I

    4/7329-Jul-02 Information Technology for

    Mana ement

    4

    A form that uses an ADO data control

    Description

    AnADOdata controldefines the recordsetfor a

    form and provides functions for navigating,displaying, adding, and updating records.

    Bound controls automatically display the valuesin the fields in the current record of the recordset

    thats defined by a data control.

  • 7/27/2019 Database Access Using ADO-I

    5/73

    29-Jul-02 Information Technology for

    Mana ement

    5

    Updating records with a data control

    The user can change the data in any one of thebound controls.

    Then, when the user clicks on one of the

    navigation buttons in the data control to move toanother record, the current record is automatically

    updated.

    If the user closes the form before moving toanother record, though, the changes are lost.

    Deleting records with a data control

    Some functions, like deleting records, arent builtinto the data control.

    To provide for these functions, you use Visual

    Basic code.

  • 7/27/2019 Database Access Using ADO-I

    6/73

    29-Jul-02 Information Technology for

    Mana ement

    6

    TwoData Bound Control

    Would be revisiting ADO Data Control soon

  • 7/27/2019 Database Access Using ADO-I

    7/73

    29-Jul-02 Information Technology for

    Mana ement

    7

    Data Bound Controls

    Controls that are tied to database fields and

    are generally not available for free-forminput.

    they automatically display database fields.

    (Data aware controls is a synonym.) Data-Bound controls on the form:

    Set the bound controls DataSourceproperty

    to point to the data control

    set the bound controls DataFieldproperty tothe database field it is to display

  • 7/27/2019 Database Access Using ADO-I

    8/73

    29-Jul-02 Information Technology for

    Mana ement

    8

    Data Bound Controls (contd) The DataChanged property is set to True whenever a bound

    controls contents are changed by the user. Before ending a program, be sure to check the DataChanged

    property of every bound control to see if the user made

    changes. As data is displayed in the bound controls, theDataChanged property is set to False.

    If the user or any other operation changes the value in thebound control, the DataChanged property is set to True.

    Simply moving to another record doesn't affect theDataChanged property.

    When the data control starts to move to a different record,the Validate event occurs.

    If DataChanged is True for any bound control, the datacontrol automatically invokes the Edit and Update methods topost the changes to the database.

    If you don't wish to save changes from a bound control tothe database, you can set the DataChanged property to

    False in the Validate event

  • 7/27/2019 Database Access Using ADO-I

    9/73

    29-Jul-02 Information Technology for

    Mana ement

    9

    Data BoundControls Special controls with properties established by

    database fields.

    A data bound control is needed for each field (column)in the Recordset (database table) we need to view.

    Most of the standard Visual Basic tools can be usedas data bound controls

    Label: used to provide display-only access to a

    specified text data field.Caption property is data bound. Text Box: used to provide read/write access to aspecified text data field. Text property is data bound.

    Check Box: Used to provide read/write access to a

    Boolean field. Value property is data bound. Picture Box & Image Box: Used to display a graphical

    image from a bitmap, icon, gif, jpeg, or metafile file.Provides read/write access to a image/binary data field.Picture property is data bound.

  • 7/27/2019 Database Access Using ADO-I

    10/73

    29-Jul-02 Information Technology for

    Mana ement

    10

    Data BoundControls (contd) Three custom data bound controls,

    data bound versions of the standard list box (DataList), thestandard combo box (DataCombo), and the standard grid control(DataGrid).

    Properties: To establish the connection of the data bound control to adatabase, we use a few properties:

    DataChanged: Indicates whether a value displayed in a boundcontrol has changed.

    DataField: Specifies the name of a field in the table pointed to bythe respective data control.

    DataSource: Specifies which data control the control is bound to(indirectly specifying the database table).

    If the data in any data bound control is changed and the usermoves to another record in the database, the database willautomatically be updated with the new data (assuming it is notReadOnly).

    Be aware of this - it is an extremely powerful feature of the

    data control, but also a potential source of problems.

  • 7/27/2019 Database Access Using ADO-I

    11/73

    29-Jul-02 Information Technology for

    Mana ement

    11

    Data BoundControls (contd) Steps in placing the controls on a form:

    Draw the bound control on the same form as the data

    control to which it will be bound.

    Set the DataSource property. Click on the drop-down arrowto list the data controls on your form. Choose one.

    Set the DataField property. Click on the drop-down arrow to

    list the fields associated with the selected data control

    records. Make your choice.

    Set all other properties, as needed.

  • 7/27/2019 Database Access Using ADO-I

    12/73

    29-Jul-02 Information Technology for

    Mana ement

    12

    An Example

  • 7/27/2019 Database Access Using ADO-I

    13/73

    29-Jul-02 Information Technology for

    Mana ement

    13

    Back to

    ADO Data Control

  • 7/27/2019 Database Access Using ADO-I

    14/73

    29-Jul-02 Information Technology for

    Mana ement

    14

    ADO Data Control The data control can perform the following tasks:

    Connect to a database.

    Open a specified database table.

    Create a virtual table based on a database query. Pass database fields to other Visual Basic tools, fordisplay or editing. Such tools are bound to thedatabase, or data bound controls.

    Add new records, delete records, or update records. Trap any errors that may occur while accessing data.

    Close the database.

    As a rule, you need one data control for everydatabase table, or virtual table, you need access to. One row of the table is accessible to each data control

    at any one time. This is referred to as the current record

  • 7/27/2019 Database Access Using ADO-I

    15/73

    29-Jul-02 Information Technology for

    Mana ement

    15

    ADO Data Control

    When an ADO data control is placed on a form, itappears with the assigned caption and four arrowbuttons:

    Move to first/previous/last/next record

    The arrows are used to navigate through the tablerecords (rows).

    The buttons can be used to move to the beginning ofthe table, the end of the table, or from record torecord.

    In most applications, the data control never appearson the form its Visible property is almost alwaysFalse.

  • 7/27/2019 Database Access Using ADO-I

    16/73

    29-Jul-02 Information Technology for

    Mana ement

    16

    ADO Data Control Properties

    The ADO data control is connected to a database simplybe setting a few properties. Important properties of thisdata control are:

    Align: Determines where data control is displayed. Caption: Phrase displayed on the data control.

    CommandType: Establishes source of Recordset (table or query).

    ConnectionString: Contains the information used to establish aconnection to a database.

    EditMode: Read-only at run-time. Indicates current state of editing for thecurrent record.

    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 controls ConnectionStringand RecordSource properties. Run-time only.

    RecordSource: Determines the table (or virtual table) the data control isattached to.

    Visible: Establishes whether the data control appears on the form at run-

    time

  • 7/27/2019 Database Access Using ADO-I

    17/73

    29-Jul-02 Information Technology for

    Mana ement

    17

    More ADO data control properties

    Property Des cription

    UserName If a user name isnt included in the

    ConnectionString property, it must be

    specified for this property.Password If a password isnt included in the

    ConnectionString property, it must be

    specified for this property.

    EOFAction Determines what happens when the user

    tries to move past the last record in the

    recordset.

    BOFAction Determines what happens when the user tries to move past the first record in the

    recordset.

  • 7/27/2019 Database Access Using ADO-I

    18/73

    29-Jul-02 Information Technology for

    Mana ement

    18

    Some of the data properties of a bound control

    Property Des cription

    DataSource Identifies the data control that defines the

    recordset you want the control bound to.

    DataField Identifies the field in the recordset that youwant the control bound to.

  • 7/27/2019 Database Access Using ADO-I

    19/73

    29-Jul-02 Information Technology for

    Mana ement

    19

    ConnectionString Property

    After placing a data control on a form, weset the ConnectionStringproperty.

    The ADO data control can connect to a

    variety of database types. There are three ways to connect to adatabase:

    using a data link, using an ODBC data source, or

    using a connection string.

  • 7/27/2019 Database Access Using ADO-I

    20/73

    29-Jul-02 Information Technology for

    Mana ement

    20

    Two dialog boxes for building a connection string

  • 7/27/2019 Database Access Using ADO-I

    21/73

    29-Jul-02 Information Technology for

    Mana ement

    21

    ConnectionString Property

    Visual Basic can build the connection string for us. The steps to create our example connection string

    are: Start a new Visual Basic project and place an ADO Data Control onthe form.

    Go to the Properties Window, click on the Connection String. Clickon the ellipsis that appears. The Property Pages window appears.

    Choose Use Connection Stringand click the Build button. TheData Link Properties window appears. Choose the Provider tab and select Microsoft Jet 3.51 OLE DB

    Provider (an Access database). Click the Next button to go to the Connection tab.

    Click the ellipsis and use the Select Access Database dialog box tochoose the BIBLIO.MDB file in your working directory. ClickOpen.

    Click Test Connection. Then, click OK (assuming it passed). ClickOK in the Property Pages window. The connection string is builtand assigned to the ConnectionStringproperty of the data control.

  • 7/27/2019 Database Access Using ADO-I

    22/73

    29-Jul-02 Information Technology for

    Mana ement

    22

    ADO Data Control Events

    Events that are triggered at various times during databaseaccess, where we write code to perform specific neededtasks. WillMove: Triggers before record pointer is moved from one row to

    another.

    MoveComplete: Event triggered after record pointer has been moved fromone row to another.

    EndofRecordset: Triggers when the record pointer is moved past the lastrecord in the recordset.

    WillChangeRecordset: Triggers before a change is made to therecordset. Used to trap unwanted changes.

    RecordsetChangeComplete: Triggers after a change is made torecordset.

    WillChangeRecord: Triggers before updates for the current row are sentto the data source.

    RecordChangeComplete: Triggers after updates for the current row aresent to the data source.

    WillChangeField: Triggers before the current field in the recordset isupdated.

    FieldChangeComplete: Triggers after the current field in the recordsethas been updated

  • 7/27/2019 Database Access Using ADO-I

    23/73

    29-Jul-02 Information Technology for

    Mana ement

    23

    DAO vs. ADO ?

    The primary difference between the two data

    controls is in the properties used to connect to a

    database.

    The DAO control connects to the database using the

    DatabaseName property while the ADO control uses

    the ConnectionString.

    To construct a Recordset, the DAO control uses theRecordSource property. The ADO control requires

    setting two properties: RecordSource and

    CommandType.

    The ADO data control offers more event procedures

    than the DAO control to allow more complete control

    over database management

  • 7/27/2019 Database Access Using ADO-I

    24/73

  • 7/27/2019 Database Access Using ADO-I

    25/73

  • 7/27/2019 Database Access Using ADO-I

    26/73

    29-Jul-02 Information Technology for

    Mana ement

    26

    ADO Recordset Properties

    Can only be accessed at run-time. To refer to a Recordset property, use a 'double-dot' notation.

    e.g., if you have a data control named datExample, to referto a property named PropertyName, the notation is:

    datExample.Recordset.PropertyName

    Important data control Recordset properties are: AbsolutePosition: Long integer that either gets or sets the

    position of the current record.

    BOF: Returns True when the current record is positioned beforeany data.

    Bookmark: Sets or returns a bookmark to the current record.Used as a place marker in database management tasks.

    EditMode: Indicates the state of editing for the current record. EOF: Returns True when the current record is positioned past any

    data.

    RecordCount: The total number of records in the Recordset.

  • 7/27/2019 Database Access Using ADO-I

    27/73

  • 7/27/2019 Database Access Using ADO-I

    28/73

    29-Jul-02 Information Technology for

    Mana ement

    28

    Example: Recordset Navigation

    cmdPrevious_Click event:Private Sub cmdPrevious_Click()

    datTitles.Recordset.MovePrevious

    If datTitles.Recordset.BOF ThendatTitles.Recordset.MoveFirst

    End If

    End Sub

    cmdNext_Click event:Private Sub cmdNext_Click()

    datTitles.Recordset.MoveNext

    If datTitles.Recordset.EOF Then

    datTitles.Recordset.MoveLast

    End If

    End Sub

  • 7/27/2019 Database Access Using ADO-I

    29/73

    29-Jul-02 Information Technology for

    Mana ement

    29

    Go toADO Data Environment

  • 7/27/2019 Database Access Using ADO-I

    30/73

    29-Jul-02 Information Technology for

    Mana ement

    30

    ThreeADO Object Model

  • 7/27/2019 Database Access Using ADO-I

    31/73

    29-Jul-02 Information Technology for

    Mana ement

    31

    The ActiveX Data Object (ADO) modelConnection

    Recordset

    Fields Field

    Command

    Parameters

    Errors Error

    Parameter

  • 7/27/2019 Database Access Using ADO-I

    32/73

    29-Jul-02 Information Technology for

    Mana ement

    32

    ADO concepts

    The Connection object represents a connection toa data source.

    A Recordset object represents a set of records

    returned from a query. You can use the Fields collection of a Recordset

    object to refer to specific fields in the recordset.

    A

    collection

    is simply a set of objects of the sametype.

    A Command object contains the definition of acommand, such as a SQL statement, the name of

    a table, or the name of a stored procedure.

    You can use the Parameters collection of aCommand object to create parameter queries or to

    specify arguments for a stored procedure.

  • 7/27/2019 Database Access Using ADO-I

    33/73

    29-Jul-02 Information Technology for

    Mana ement

    33

    ADO concepts (continued)

    The Errors collection contains one or more Errorobjects that contain information about the most

    recent errors that occurred in response to an ADO

    operation.

    You can use these objects to get moreinformation than the Visual Basic Err object

    provides.

    The ADO model lets you access a data sourceusing an object-oriented interface.

    That means you can use the same syntax to

    access data objects that you use to access objectslike forms and controls.

    The ADO model also provides a variety ofproperties, methods, and events for working with

    the ActiveX data objects.

  • 7/27/2019 Database Access Using ADO-I

    34/73

    29-Jul-02 Information Technology for

    Mana ement

    34

    How does ADO work ?

    ADO is a component for accessing databases

    It exposes a few very flexible objects, which exposetheir own properties, methods, and recognize events

    The structure of the ADO object model reflects the

    operations we perform on a database, We can even guess these objects and their names once

    we understand what it takes to access and update a

    database. First step to using ADO is to connect to a database

    This connection object is our gateway to the database

  • 7/27/2019 Database Access Using ADO-I

    35/73

    29-Jul-02 Information Technology for

    Mana ement

    35

    Common ADO properties

    Property ObjectConnectionString Connection

    Provider Connection

    DefaultDatabase Connection

    CursorLocation Connection

    Recordset

    BOFEOF

    Recordset

    CursorType Recordset

    LockType Recordset

    RecordCount Recordset

    C ADO th d

  • 7/27/2019 Database Access Using ADO-I

    36/73

    29-Jul-02 Information Technology for

    Mana ement

    36

    Common ADO methods

    Method Object

    Open Connection

    Recordset

    AddNew Recordset

    Update Recordset

    Delete Recordset

    MoveFirst

    MoveLast

    MovePrevious

    MoveNext

    Recordset

    Requery Recordset

    Close Connection

    Recordset

    T i l d l ti f ADO i bl

  • 7/27/2019 Database Access Using ADO-I

    37/73

    29-Jul-02 Information Technology for

    Mana ement

    37

    Typical declarations for ADO variablesDim cnAP As Connection

    Dim rsVendors As Recordset

    Typical assignment statements for ADOvariablesSet cnAP = New Connection

    Set rsVendors = New Recordset

    Set rsVendors = Nothing

    Typical statements for working withADO variablesrsVendors.Open "Vendors",cnAP,adOpenKeyset, _

    adLockOptimistic,adCmdTable

    txtName = rsVendors!VendorName

    If rsVendors.EOF Then rsVendors.MoveLast

    rsVendors.Close

    D i i

  • 7/27/2019 Database Access Using ADO-I

    38/73

    29-Jul-02 Information Technology for

    Mana ement

    38

    Description

    Use the Dim statement (Private or Public) to declare an objectvariable for an ADO object

    After above declaration, we use the Set statement to create

    an instance of the object and assign a reference to the

    object to the variable. To do this, we use the New keyword and the name of the ADO

    object

    After creating an instance of an object, we can refer to its

    properties, methods, and events in the code.

    To disassociate a variable from the object it refers to, assign a

    value of Nothing to the value. Then, the system resources

    associate with the object are released. To refer to a field in a recordset, code the recordset name, the

    bang operator (!), and the field name

    as in, rsVendors!VendorName

  • 7/27/2019 Database Access Using ADO-I

    39/73

    29-Jul-02 Information Technology for

    Mana ement

    39

    A procedure that deletes a record from the datasource associated with a data controlPrivate Sub cmdDelete_Click()

    If MsgBox("Do you want to delete this record?", _

    vbYesNo + vbDefaultButton2 + vbQuestion) _= vbYes Then

    adoVendors.Recordset.Delete

    adoVendors.Recordset.MoveNext

    If adoVendors.Recordset.EOF Then

    adoVendors.Recordset.Requery

    adoVendors.Recordset.MoveLast

    End If

    End If

    End Sub

  • 7/27/2019 Database Access Using ADO-I

    40/73

    29-Jul-02 Information Technology for

    Mana ement

    40

    Three

    UnderstandingCursors & Recordsets

    C & R d t

  • 7/27/2019 Database Access Using ADO-I

    41/73

    29-Jul-02 Information Technology for

    Mana ement

    41

    Cursors & Recordsets

    There is a direct relationship between SQL Server cursors andVB Recordsets. Every time we issue a SELECT statement, SQL Server

    retrieves the qualifying rows and returns them to the caller,

    which is a stored procedure or a Visual Basic application. This set of rows is called a cursor When the cursor is passed to the VB application, its stored in a

    Recordset object. The cursor contains the info. retrieved from the DB, the raw

    information. A Recordset is an ADO object that stores these rows. It contains

    the functionality we need to access these rows in the form ofproperties and methods.

    A recordset is simply an object that references a cursor. It exposes a number of methods and properties we can use

    to navigate the cursor (not the Recordset) and edit the rowsof the underlying cursor.

    C & R d

  • 7/27/2019 Database Access Using ADO-I

    42/73

    29-Jul-02 Information Technology for

    Mana ement

    42

    Cursors & Recordsets

    A typical application sets up a connection to adatabase and executes commands through thisconnection, but it spends most of its time processing

    the rows returned by the DBMS After establishing a connection to the database and

    preparing the command object, we can execute thecommand and retrieve the cursor. However, wemust prepare an object where the cursor will bestored. This object is a Recordset variable, that must be

    declared as: Dim RS as ADODB.Recordset Then execute the command with theExecute method

    and assign the cursor returned to the RS variable: Set RS = Cmd.Execute

    f

  • 7/27/2019 Database Access Using ADO-I

    43/73

    29-Jul-02 Information Technology for

    Mana ement

    43

    Types of Cursors Different applications have different requirements,

    which get reflected by the cursor-related propertiesas well as by the LockType property

    Cursors are categorized according to their type(CursorType property) and where they reside(CursorLocation property)

    The type of cursor determines how fresh the cursoris, i.e., whether the application can see changes madeto the cursor by other users or not.

    If the cursor resides on the client,then its type is static Other types apply to cursors that reside on server.

    C L ti ti

  • 7/27/2019 Database Access Using ADO-I

    44/73

    29-Jul-02 Information Technology for

    Mana ement

    44

    CursorLocation options

    Option Des criptionadUseClient The cursor and its associated result set

    reside on the client.

    adUseServer The cursor and its associated result setreside on the server.

    Note

    If we use client-side cursors (adUseClient), Visual Basic

    automatically sets the cursor type to adOpenStatic withoutnotifying us, no matter what we set the CursorType to.

    CursorType options

  • 7/27/2019 Database Access Using ADO-I

    45/73

    29-Jul-02 Information Technology for

    Mana ement

    45

    CursorType options

    Option Des criptionadOpenDynamic Opens a dynamic cursor, which includes

    changes, additions, and deletions made to

    the database by other users.

    Uses keys to identify individual records.

    Cannot be used to create sorted result sets

    from SQL Server data.

    adOpenKeyset Opens a keyset cursor, which includeschanges made to the database by other

    users.

    Additions made by other users arentvisible, but records deleted by other users

    are no longer accessible.

    Uses keys to identify individual records.

  • 7/27/2019 Database Access Using ADO-I

    46/73

    29-Jul-02 Information Technology for

    Mana ement

    46

    CursorType options (continued)

    Option Description

    adOpenStatic Opens a static cursor, which doesnt

    include changes, additions, and deletions

    made to the database by other users.

    This is the only type of cursor that can be

    created on the client with ADO.

    adOpenForwardOnly Opens a forward-only cursor.This cursor is like a static cursor, but you

    can only scroll forward through the

    records.This type of cursor isnt available when

    you define a recordset using a data control.

  • 7/27/2019 Database Access Using ADO-I

    47/73

    29-Jul-02 Information Technology for

    Mana ement

    47

    Three

    ADO Saga Continues

    LockType options

  • 7/27/2019 Database Access Using ADO-I

    48/73

    29-Jul-02 Information Technology for

    Mana ement

    48

    LockType options

    Option Des criptionadLockReadOnly Data can be viewed, but not modified.

    When used with SQL Server data, this

    causes a shared lock to be placed on the

    records so other users can access andchange the data at the same time.

    adLockPessimistic Causes the records to be locked

    immediately so other users cant change

    them.

    When used with SQL Server data, this

    causes an update lock to be placed on the

    records when theyre retrieved. Theupdate lock is upgraded to an exclusive

    lock when the records are actually

    updated.

  • 7/27/2019 Database Access Using ADO-I

    49/73

    29-Jul-02 Information Technology for

    Mana ement

    49

    LockType options (continued)

    adLockOptimistic Causes the records to be locked when

    theyre updated.

    When used with SQL Server data, this

    causes a shared lock to be placed on therecords when theyre retrieved. Then,

    when the Update method is issued, the

    shared lock is upgraded to an update lock.

    And when the records are actuallyupdated, the update lock is upgraded to an

    exclusive lock.

    adLockBatchOptimistic Used for updating records in batchesinstead of one at a time.

    An Unbound form using code to maintain vendor records

  • 7/27/2019 Database Access Using ADO-I

    50/73

    29-Jul-02 Information Technology for

    Mana ement

    50

    An Unbound form using code to maintain vendor records

    Description The navigation buttons are an array of command buttons.

    When a record is first displayed, the Update button is disabled. As soonas the user makes a change to the data in the form, however, the Update

    button is enabled and the Add, Delete, and navigation buttons aredisabled.

    To save the changes, the user must click on the Update button or pressthe Enter key to activate the Update button.

    Description (continued)

  • 7/27/2019 Database Access Using ADO-I

    51/73

    29-Jul-02 Information Technology for

    Mana ement

    51

    Description (continued)

    To cancel the changes, the user can press the Esc key. When the user clicks on the Add button, the controls are

    cleared, the Update button is enabled, and the Add,

    Delete, and navigation buttons are disabled.

    After the data for the new record is entered into theform, the user can save the record by clicking on the

    Update button or pressing the Enter key.

    To cancel the addition, the user can press the Esc key.

    If the user clicks on the Update button to add a newrecord or modify an existing record and a required field

    hasnt been entered, a message box is displayed

    identifying the field.

    When the user presses the Delete key, a dialog box isdisplayed to confirm the delete operation. If the user

    confirms the operation, the record is deleted and the

    next record in the recordset is displayed.

    F ti th t id d th h d

  • 7/27/2019 Database Access Using ADO-I

    52/73

    29-Jul-02 Information Technology for

    Mana ement

    52

    Functions that are provided through code

    Function Method orstatement

    When executed

    Open connection Open method When the form is loaded

    Open recordset Open method When the form is loaded

    Recordset

    navigation

    MoveFirst,

    MovePrevious,

    MoveNext,

    MoveLast

    When the user clicks on a

    navigation button or

    when other events require

    this movement

    Move values

    from fields to

    controls

    Assignment

    statements

    When the recordset is

    opened, when the user

    clicks on a navigation

    button, when a record isdeleted, and when

    changes to a record are

    canceled

    More functions that are provided through code

  • 7/27/2019 Database Access Using ADO-I

    53/73

    29-Jul-02 Information Technology for

    Mana ement

    53

    More functions that are provided through code

    Func tio n Me tho d o rs tate m e nt

    Wh e n e x e c u te d

    Clear control

    values

    Assignment

    statements

    When the user wants to

    add a record

    Add a newrecord to the

    recordset

    AddNewmethod

    When the user wants toadd a record

    Move values

    from controls tocurrent record,

    and update the

    recordset

    Assignment

    statements,Update method

    When the user indicates

    that recordset should beupdated with the data for

    a new record or the

    changes to an old record

    Close a

    connection or

    recordset

    Close method W hen the connection or

    recordset is no longer

    needed

  • 7/27/2019 Database Access Using ADO-I

    54/73

    29-Jul-02 Information Technology for

    Mana ement

    54

    Open method syntax for a Connection objectconnection.Open [ConnectionString][, UserID][, Password]

    ConnectionString arguments for SQL Server

    Arg ume nt De s c riptio n

    Provider The name of the OLE DB provider

    (SQLOLEDB)

    Server/Data

    Source

    The name of the server where the database

    residesDatabase/

    Initial Catalog

    The name of the database

    UID/UserID The user name to use when connecting to

    the data source

    PWD/Password The password to use when connecting to the

    data source

  • 7/27/2019 Database Access Using ADO-I

    55/73

    29-Jul-02 Information Technology for

    Mana ement

    55

    Statements that open a connection to a SQLServer databaseDim cnAP As Connection

    Set cnAP = New Connection

    cnAP.CursorLocation = adUseClient

    cnAP.Open "Provider=SQLOLEDB;Server=mmaserver;" _

    & "Database=AccountsPayable", "ed", "abc4xyz"

  • 7/27/2019 Database Access Using ADO-I

    56/73

    29-Jul-02 Information Technology for

    Mana ement

    56

    Open method syntax for a Recordset objectrecordset.Open [Source][, ActiveConnection][, CursorType][, LockType][, Options]

    Argument Des cription

    Source A SQL statement, the name of a table, or the name of a stored procedure.

    ActiveConnection A valid Connection object or string.

    CursorType The type of cursor to be used for therecordset

    LockType The type of locking to be used for the

    recordset

    Options The type of information specified in theSource argument

  • 7/27/2019 Database Access Using ADO-I

    57/73

    29-Jul-02 Information Technology for

    Mana ement

    57

    Statements that open a recordset with a SELECTstatement and a Connection objectDim rsVendors As Recordset, strSQL As String

    Set rsVendors = New Recordset

    strSQL = "SELECT * FROM Vendors ORDER BY VendorName"

    rsVendors.Open strSQL, cnAP, adOpenKeyset, _adLockOptimistic, adCmdText

    Statements that open the same recordset using aconnection string and no Connection objectDim strConnection As String

    strConnection = "Provider=SQLOLEDB;Server=mmaserver;" _

    & "UID=ed;PWD=abc4xyz;Database=AccountsPayable"

    rsVendors.Open strSQL, strConnection, adOpenKeyset, _

    adLockOptimistic, adCmdText

    The properties for two controls in an array

  • 7/27/2019 Database Access Using ADO-I

    58/73

    29-Jul-02 Information Technology for

    Mana ement

    58

    Description

    To create a control array, you add two or more controls of

    the same type to the form. Then, you change the names of the controls so theyre all the

    same and Visual Basic sets the Index property of each

    control so its unique.

    How to use a control array

  • 7/27/2019 Database Access Using ADO-I

    59/73

    29-Jul-02 Information Technology for

    Mana ement

    59

    To refer to a control in an array, you use the controlname followed by its index number in parentheses,

    starting with zero for the first control in the array as in

    this example:

    cmdNavigate(0)

    The controls in a control array are treated as a group. Sowe code a single event procedure for the entire array

    When an event occurs on a control in an array, VisualBasic passes an argument to the event procedure that

    contains the index of the control that the event occurred

    on. Then, you can use that index to determine the

    processing thats done.

    Code for working with the control array

  • 7/27/2019 Database Access Using ADO-I

    60/73

    29-Jul-02 Information Technology for

    Mana ement

    60

    Code for working with the control array

    Private Sub cmdNavigate_Click(Index As Integer)Select Case Index

    Case 0

    rsVendors.MoveFirst

    Case 1

    rsVendors.MovePreviousIf rsVendors.BOF Then rsVendors.MoveFirst

    Case 2

    rsVendors.MoveNext

    If rsVendors.EOF Then rsVendors.MoveLast

    Case 3

    rsVendors.MoveLast

    End Select

    End Sub

    Code for the unbound Vendors form

  • 7/27/2019 Database Access Using ADO-I

    61/73

    29-Jul-02 Information Technology for

    Mana ement

    61

    Code for the unbound Vendors form

    Option Explicit 1

    Dim mcnAP As Connection

    Dim mrsVendors As Recordset

    Dim mbAddNew As Boolean

    Const msDialogTitle = "Chapter 6 - Vendors (Unbound)"

    Private Sub Form_Load() 2

    Set mcnAP = New Connection

    Set mrsVendors = New Recordset

    mcnAP.Open "Provider=SQLOLEDB;Server=mmaserver;" _

    & "Database=AccountsPayable", "ed","abc4xyz"

    mrsVendors.Open _

    "SELECT * FROM Vendors ORDER BY VendorName", _

    mcnAP, adOpenKeyset, adLockOptimistic, adCmdText

    LoadControlsSetCommandButtons True

    SetNavigationButtons True

    End Sub

  • 7/27/2019 Database Access Using ADO-I

    62/73

    29-Jul-02 Information Technology for

    Mana ement

    62

    Private Sub LoadControls() 3

    With mrsVendors

    txtName = !VendorName

    txtAddress1 = !VendorAddress1 & ""

    txtAddress2 = !VendorAddress2 & ""

    txtCity = !VendorCity

    txtState = !VendorStatetxtZipCode = !VendorZipCode

    txtContact = !VendorContact & ""

    txtPhone = !VendorPhone & ""

    End With

    End Sub

    Private Sub SetCommandButtons(bVal As Boolean) 4

    cmdAdd.Enabled = bVal

    cmdUpdate.Enabled = Not bVal

    cmdUpdate.Default = Not bValcmdDelete.Enabled = bVal

    End Sub

  • 7/27/2019 Database Access Using ADO-I

    63/73

    29-Jul-02 Information Technology for

    Mana ement

    63

    Private Sub SetNavigationButtons(bVal As Boolean) 5

    Dim i As Integer

    For i = 0 To 3cmdNavigate(i).Enabled = bVal

    Next

    End Sub

  • 7/27/2019 Database Access Using ADO-I

    64/73

    29-Jul-02 Information Technology for

    Mana ement

    64

    Private Sub cmdNavigate_Click(Index As Integer) 6With mrsVendors

    Select Case Index

    Case 0

    .MoveFirst

    Case 1

    .MovePrevious

    If .BOF Then .MoveFirst

    Case 2

    .MoveNext

    If .EOF Then .MoveLast

    Case 3

    .MoveLast

    End Select

    End With

    LoadControls

    SetCommandButtons TrueSetNavigationButtons True

    txtName.SetFocus

    End Sub

  • 7/27/2019 Database Access Using ADO-I

    65/73

    29-Jul-02 Information Technology for

    Mana ement

    65

    Private Sub cmdAdd_Click() 7mbAddNew = True

    ClearControls

    SetCommandButtons False

    txtName.SetFocus

    End Sub

    Private Sub ClearControls() 8

    txtName = ""

    txtAddress1 = ""

    txtAddress2 = ""txtCity = ""

    txtState = ""

    txtZipCode = ""

    txtContact = ""

    txtPhone = ""

    End Sub

  • 7/27/2019 Database Access Using ADO-I

    66/73

    29-Jul-02 Information Technology for

    Mana ement

    66

    Private Sub cmdUpdate_Click() 9On Error GoTo ErrorHandler

    If ValidData Then

    If mbAddNew Then mrsVendors.AddNew

    LoadRecord

    mrsVendors.UpdatembAddNew = False

    SetCommandButtons True

    SetNavigationButtons True

    txtName.SetFocus

    End If

    Exit Sub

    ErrorHandler:

    DisplayErrorMsg

    If mrsVendors.EditMode = adEditAdd Then

    mrsVendors.CancelUpdate

    End Sub

    Private Function ValidData() As Boolean 10

  • 7/27/2019 Database Access Using ADO-I

    67/73

    29-Jul-02 Information Technology for

    Mana ement

    67

    Private Function ValidData() As Boolean 10

    Dim strMessage As StringIf txtName = "" Then

    txtName.SetFocus

    strMessage = "You must enter a vendor name."

    ElseIf txtCity = "" Then

    txtCity.SetFocus

    strMessage = "You must enter a city."

    ElseIf txtState = "" Then

    txtState.SetFocus

    strMessage = "You must enter a state code."

    ElseIf txtZipCode = "" Then

    txtZipCode.SetFocus

    strMessage = "You must enter a zip code."

    Else

    ValidData = True

    End If

    If Not ValidData ThenMsgBox strMessage, vbOKOnly, msDialogTitle

    End If

    End Function

  • 7/27/2019 Database Access Using ADO-I

    68/73

    29-Jul-02 Information Technology for

    Mana ement

    68

    Private Sub LoadRecord() 11

    With mrsVendors

    !VendorName = txtName

    !VendorAddress1 = txtAddress1

    !VendorAddress2 = txtAddress2

    !VendorCity = txtCity

    !VendorState = txtState

    !VendorZipCode = txtZipCode

    !VendorContact = txtContact

    !VendorPhone = txtPhoneEnd With

    End Sub

    Private Sub cmdDelete_Click() 12

    On Error GoTo ErrorHandler

  • 7/27/2019 Database Access Using ADO-I

    69/73

    29-Jul-02 Information Technology for

    Mana ement

    69

    If MsgBox("Do you want to delete this record?", _vbYesNo + vbDefaultButton2 + vbQuestion, _

    msDialogTitle) _

    = vbYes Then

    With mrsVendors

    .Delete

    .MoveNext

    If .EOF Then

    .Requery

    .MoveLast

    End If

    LoadControlsEnd With

    End If

    SetCommandButtons True

    SetNavigationButtons True

    txtName.SetFocusExit Sub

    ErrorHandler:

    DisplayErrorMsg

    End Sub

  • 7/27/2019 Database Access Using ADO-I

    70/73

    29-Jul-02 Information Technology for

    Mana ement

    70

    Private Sub txtName_Change() 13SetNavigationButtons False

    SetCommandButtons False

    End Sub

    Private Sub txtAddress1_Change()SetNavigationButtons False

    SetCommandButtons False

    End Sub

    .

    .

    .

    Private Sub txtPhone_Change()

    SetNavigationButtons False

    SetCommandButtons False

    End Sub

    Private Sub Form_KeyDown(KeyCode As Integer, _ 14

    Shift As Integer)

  • 7/27/2019 Database Access Using ADO-I

    71/73

    29-Jul-02 Information Technology for

    Mana ement

    71

    If KeyCode = vbKeyEscape ThenLoadControls

    SetCommandButtons True

    SetNavigationButtons True

    End If

    End Sub

    Private Sub cmdExit_Click() 15

    mrsVendors.Close

    mcnAP.Close

    Set mrsVendors = Nothing

    Set mcnAP = NothingUnload frmVendors

    End

    End Sub

    Private Sub DisplayErrorMsg() 16MsgBox "Error Code: " & Err.Number & vbCrLf & _

    "Description: " & Err.Description, _

    vbOKOnly + vbCritical, msDialogTitle

    End Sub

    When bound forms are best

    Wh th f l ti l i l

  • 7/27/2019 Database Access Using ADO-I

    72/73

    29-Jul-02 Information Technology for

    Mana ement

    72

    When the forms are relatively simple

    When the built-in functions are acceptable to the users

    When you need to build an application quickly without fullfunctionality

    When unbound forms are best

    When the forms are relatively complex

    When the user interface needs to work in a way that can't be

    accomplished with bound forms When you can't get the bound forms to do what you want them to

    do without serious debugging problems (see chapter 7)

    Notes You can combine the use of bound and unbound forms.

    Unbound forms are commonly used for critical businessapplications.

    Character -- the willingness to accept responsibility for one's

  • 7/27/2019 Database Access Using ADO-I

    73/73

    29-Jul-02 Information Technology for

    Mana ement

    73

    own life -- is the source from which self-respect springs.-- Joan Didion