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

VB_V_UNIT

The document provides an overview of database connecting tools in Visual Basic, focusing on ADO, DAO, ADODC, and ADODB, detailing their components and functionalities. It includes examples of how to create and manipulate databases in Microsoft Access, as well as how to use data controls like list boxes and combo boxes for user interaction. Additionally, it covers methods for adding, editing, and deleting records, along with error handling techniques.

Uploaded by

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

VB_V_UNIT

The document provides an overview of database connecting tools in Visual Basic, focusing on ADO, DAO, ADODC, and ADODB, detailing their components and functionalities. It includes examples of how to create and manipulate databases in Microsoft Access, as well as how to use data controls like list boxes and combo boxes for user interaction. Additionally, it covers methods for adding, editing, and deleting records, along with error handling techniques.

Uploaded by

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

UNIT -V

DATABASE CONNECTING TOOLS

ADO (ACTIVEX DATA OBJECTS)

ADO is a high-level data access technology that provides a streamlined way to


connect to databases. It abstracts the complexities of database interactions and allows
developers to work with a consistent set of objects and methods. ADO is particularly
powerful for applications that require flexibility in connecting to different data sources, such
as SQL Server, Oracle, and Microsoft Access.

Components

ADO consists of a set of objects that can be used to connect to a database, execute
commands, and manipulate data. The primary objects include:

 Connection: Establishes a connection to a data source.


 Command: Executes a command against a data source.
 Record set: Represents the result set of a query and allows for data manipulation.
 Parameter: Represents parameters used in commands and queries.
 Error: Provides information about errors encountered during database operations.

EX:

Dim conn As New ADODB.Connection


Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
' Open connection
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\path\to\database.mdb;"
conn.Open
' Set up command
cmd.ActiveConnection = conn
cmd.CommandText = "SELECT * FROM YourTable"
' Execute command and get recordset
rs.Open cmd
' Read data
Do While Not rs.EOF
Debug.Print rs.Fields("Name").Value
rs.MoveNext
Loop
' Clean up
rs.Close
conn.Close
DAO (DATA ACCESS OBJECTS)

DAO is specifically designed for Microsoft Access databases. It offers a direct means
to interact with Access databases by providing access to database objects like tables, queries,
and records. DAO is ideal for applications that exclusively use Access as their data storage
solution.

Components

DAO consists of several key objects that help in managing data:

 Database: Represents a single database file. It provides methods to open, close, and
manipulate database tables and queries.
 Table Def: Represents the definition of a table within a database, including its fields
and indexes.
 Record set: Represents a set of records from a database table or query. It allows
navigation and manipulation of data.
 Field: Represents a single field in a record set.
 Query Def: Represents a saved query in the database.

Ex:

Dim db As DAO.Database
Dim rs As DAO.Recordset
' Open the database
Set db = OpenDatabase("C:\path\to\your\database.mdb")
' Open a recordset
Set rs = db.OpenRecordset("SELECT * FROM YourTable")
' Read data
Do While Not rs.EOF
Debug.Print rs.Fields("Name").Value
rs.MoveNext
Loop
' Clean up
rs.Close
db.Close

ADODC (ACTIVEX DATA OBJECTS DATA CONTROL)

ADODC is a control that simplifies the process of connecting to and interacting with
databases in Visual Basic applications. By using this control, developers can bind data to
visual elements like text boxes, list boxes, and combo boxes without extensive coding. This
reduces development time and complexity
Components

 Connection String: Specifies how to connect to the data source (e.g., database path,
provider).
 Record Source: Defines the SQL query or table from which to retrieve data.
 Data Control: Links the ADODC control to other UI controls for data display.
 Command Timeout: Specifies the time to wait for a command to execute before
timing out.

Ex:

Private Sub cmdFirst_Click()


ADODC1.Recordset.MoveFirst
End Sub
Private Sub cmdLast_Click()
ADODC1.Recordset.MoveLast
End Sub
Private Sub cmdNext_Click()
ADODC1.Recordset.MoveNext
End Sub
Private Sub cmdPrevious_Click()
ADODC1.Recordset.MovePrevious
End Sub

ADODB (ACTIVEX DATA OBJECTS DATABASE)

ADODB builds upon ADO, offering enhanced functionality for more complex database
operations. It is particularly useful for scenarios requiring advanced data manipulation, such
as executing stored procedures or managing transactions. ADODB supports both OLE DB
and ODBC, making it versatile for various database types.

 adEmpty (0): No data; null value.


 adTinyInt (16): A very small integer (1 byte).
 adSmallInt (2): A small integer (2 bytes).
 adInteger (3): A standard integer (4 bytes).
 adBigInt (20): A large integer (8 bytes).
 adSingle (4): A single-precision floating-point number (4 bytes).
 adDouble (5): A double-precision floating-point number (8 bytes).
 adCurrency (6): A currency value (8 bytes, fixed point).
 adDecimal (14): A decimal value with a specified precision and scale.
 adNumeric (131): A fixed-point number.
Features:

 Data Source Independence: Supports various database types through OLE DB,
allowing developers to connect to multiple data sources without changing application
code.
 Rich Object Model: Offers a comprehensive set of objects, including connections,
commands, record sets, and more.
 Support for Transactions: Provides robust transaction management, enabling
multiple operations to be grouped into a single unit.
 Asynchronous Processing: Allows for non-blocking database operations, improving
application responsiveness.

Ex:

Dim cmd As ADODB.Command


Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
' Add a parameter with a specific data type
cmd.Parameters.Append cmd.CreateParameter("UserName", adVarChar,
adParamInput, 50, "JohnDoe")
cmd.Parameters.Append cmd.CreateParameter("UserAge", adInteger,
adParamInput, , 30)
cmd.CommandText = "INSERT INTO Users (Name, Age) VALUES (?, ?)"
cmd.Execute

CREATING A DATABASE FILE IN MICROSOFT ACCESS

To start working with databases in Visual Basic, you first need to create a database
file in Microsoft Access.

Steps to Create a Database

1. Open Microsoft Access: Launch Access and select "New" to create a new
database.
2. Create a Database File: Choose a name and location for your database file (.mdb
or .accdb) and click "Create."
3. Define Tables:
o Go to the "Table Design" view to create a new table.
o Define fields (e.g., ID, Name, Address) and set appropriate data types
(e.g., Text, Number, Date/Time).
4. Set Primary Keys: Identify a primary key field to uniquely identify records (e.g.,
ID).
Example Table Structure

Field Name Data Type


ID AutoNumber (Primary Key)
Name Text
Address Text
Phone Text

Saving the Database

After creating the tables and defining the structure, save the database. Ensure
to back it up regularly to prevent data loss.

USING DATA CONTROLS IN VISUAL BASIC

Once your database is set up, you can integrate data controls in your Visual Basic
application to connect and manipulate the data.

Adding ADODC Control

1. Open Visual Basic: Create or open your project.


2. Add the ADODC Control:
o In the toolbox, select the ADODC control and place it on your form.
3. Setting Properties:
o Set the ConnectionString property to point to your Access database file.
This can be done through the properties window or programmatically.
o Set the RecordSource property to specify the table or query you want to
use.

Example of Setting the Connection String

ADODC1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\path\to\your\database.mdb;"
ADODC1.RecordSource = "SELECT * FROM YourTable"

USING LIST BOX AND COMBO BOX

Data controls can be utilized to create user-friendly interfaces for displaying and
selecting data.

LIST BOX

A list box allows users to view multiple records. To bind a list box to the ADODC
control:

1. Add a List Box to your form.


2. Set the List Field property to the field you want to display (e.g., Name).
Types of List Boxes

 Single-Selection List Box: Allows users to select only one item at a time.
When a user selects a new item, the previous selection is automatically
deselected.
 Multi-Selection List Box: Allows users to select multiple items
simultaneously, typically by holding down the Ctrl or Shift key while clicking.

Properties

When working with list boxes, several properties are essential:

 Items: The collection of items displayed in the list box. You can add or
remove items programmatically.
 Selected Index: The index of the currently selected item(s). In a multi-
selection list box, this can be an array of indices.
 Selected Item: The actual value of the currently selected item.
 Multi Select: A property that indicates whether multiple selections are
allowed (True) or not (False).
 Text: The text of the currently selected item.

Ex:

Private Sub Form_Load()


' Adding items to the list box
ListBox1.AddItem "Item 1"
ListBox1.AddItem "Item 2"
ListBox1.AddItem "Item 3"
End Sub

COMBO BOX

A combo box provides a dropdown list for users to select an item. To bind a
combo box:

1. Add a Combo Box to your form.


2. Set the List Field property to the field for display (e.g., Name).

Types of Combo Boxes

 Drop-Down Combo Box: Displays a list of options when the user clicks on it.
The user can select one item or type their own entry.
 Drop-Down List: Similar to the drop-down combo box, but the user cannot enter
their own values; they can only select from the list.
Properties

When working with combo boxes, several properties are essential:

 Items: The collection of items displayed in the list. You can add, remove, or
modify items programmatically.
 Selected Index: The index of the currently selected item. Useful for retrieving the
selected value or determining user selections.
 Selected Item: The actual value of the currently selected item.
 Text: The text displayed in the combo box, which can either reflect the selected
item or user input.
 Drop Down Style: Determines whether the combo box allows free text entry
(simple) or restricts users to the items in the list (drop-down).

Private Sub Form_Load()


' Adding items to the combo box
ComboBox1.AddItem "Option 1"
ComboBox1.AddItem "Option 2"
ComboBox1.AddItem "Option 3"
End Sub

Example of Binding

List1.ListField = "Name"

Combo1.ListField = "Name"

Handling Selections

To handle user selections, you can add event handlers for the list box and
combo box. For example:

Private Sub List1_Click()


txtName.Text = List1.List(List1.ListIndex)
End Sub
Private Sub Combo1_SelectedIndexChanged()
txtName.Text = Combo1.Text
End Sub

DATA FOUND CONTROL

The Data Found control provides navigation through records in your bound data
control. It typically includes buttons for navigating to the first, previous, next, and last
records.

Adding Data Found Control

1. Drag and drop the Data Found control onto your form.
2. Link it to your ADODC control to enable navigation.
Example of Data Navigation

You can add code to handle navigation buttons to ensure users can traverse records
smoothly:

Private Sub cmdFirst_Click()


ADODC1.Recordset.MoveFirst
End Sub
Private Sub cmdLast_Click()
ADODC1.Recordset.MoveLast
End Sub
Private Sub cmdNext_Click()
ADODC1.Recordset.MoveNext
End Sub
Private Sub cmdPrevious_Click()
ADODC1.Recordset.MovePrevious
End Sub

UPDATING DATA IN THE DATABASE

Adding Records

To add new records, you can use the Add New method of the ADODC control:

Private Sub cmdAdd_Click()


ADODC1.Recordset.AddNew
ADODC1.Recordset.Fields("Name") = txtName.Text
ADODC1.Recordset.Fields("Address") = txtAddress.Text
ADODC1.Recordset.Update
MsgBox "Record Added"
End Sub
Editing Records

To edit existing records, navigate to the desired record and modify the fields:

Private Sub cmdEdit_Click()


ADODC1.Recordset.Edit
ADODC1.Recordset.Fields("Name") = txtName.Text
ADODC1.Recordset.Update
MsgBox "Record Updated"
End Sub
Deleting Records

To delete the current record, use the Delete method:

Private Sub cmdDelete_Click()


ADODC1.Recordset.Delete
MsgBox "Record Deleted"
End Sub

Error Handling

When working with databases, it's essential to implement error handling to manage
unexpected situations gracefully. Here’s a simple example of error handling:

Private Sub cmdAdd_Click()


On Error GoTo ErrorHandler
ADODC1.Recordset.AddNew
ADODC1.Recordset.Fields("Name") = txtName.Text
ADODC1.Recordset.Fields("Address") = txtAddress.Text
ADODC1.Recordset.Update
MsgBox "Record Added"
Exit Sub
Error Handler:
MsgBox "An error occurred: " & Err.Description
End Sub

You might also like