ADO - Building Reusable ADO Data Access Layers (DAL)

Introduction

In every database-driven application, communication between the application and the database is essential. A simple application may contain only a few database operations, but as the application grows, managing database code becomes increasingly difficult. Writing database connection code repeatedly in different parts of the application leads to code duplication, poor maintainability, and a higher chance of errors.

A Data Access Layer (DAL) is a software design pattern that centralizes all database-related operations into a single layer. Instead of allowing every form or module to communicate directly with the database, the application interacts with the DAL, which handles all database operations using ADO. This approach creates reusable, organized, and maintainable code.


What is a Data Access Layer?

A Data Access Layer (DAL) is a separate component of an application that manages all communication between the application and the database.

Its responsibilities include:

  • Opening database connections

  • Closing database connections

  • Executing SQL queries

  • Executing stored procedures

  • Retrieving records

  • Inserting new records

  • Updating existing records

  • Deleting records

  • Handling transactions

  • Managing database errors

The user interface or business logic does not directly interact with the database. Instead, it sends requests to the DAL.


Why Use a Data Access Layer?

Without a DAL, database code is scattered across multiple forms, reports, and modules.

Example without a DAL:

Employee Form
     |
     |----Open Connection
     |----Execute Query
     |----Close Connection

Customer Form
     |
     |----Open Connection
     |----Execute Query
     |----Close Connection

Product Form
     |
     |----Open Connection
     |----Execute Query
     |----Close Connection

Each module repeats similar code.

With a DAL:

Employee Form
          |
Customer Form
          |
Product Form
          |
     Data Access Layer
          |
       Database

All database operations are handled in one place.


Objectives of DAL

A good Data Access Layer should:

  • Reduce duplicate code

  • Improve code readability

  • Simplify maintenance

  • Increase application security

  • Improve scalability

  • Separate business logic from database logic

  • Make testing easier

  • Allow database changes with minimal code modification


Components of a Data Access Layer

A DAL generally contains several reusable methods.

Connection Management

This component opens and closes database connections.

Example methods:

OpenConnection()

CloseConnection()

Instead of writing connection code repeatedly, every module uses these methods.


Query Execution

The DAL executes SQL statements.

Example methods:

ExecuteQuery()

ExecuteNonQuery()

ExecuteScalar()

These methods perform common database tasks.


Record Retrieval

This component retrieves records from the database.

Example:

GetEmployees()

GetCustomers()

GetProducts()

Each method returns the requested data.


Insert Operations

The DAL contains methods for adding new records.

Example:

InsertEmployee()

InsertCustomer()

InsertProduct()

Each method performs validation and executes the INSERT statement.


Update Operations

Reusable update methods simplify record modification.

Example:

UpdateEmployee()

UpdateCustomer()

UpdateProduct()

Delete Operations

Deletion is also centralized.

Example:

DeleteEmployee()

DeleteCustomer()

DeleteProduct()

Typical DAL Architecture

Presentation Layer
        |
Business Logic Layer
        |
Data Access Layer
        |
ADO Objects
        |
Database

Presentation Layer

Contains forms, reports, and user interfaces.

Example:

  • Login Form

  • Employee Form

  • Product Form


Business Logic Layer

Contains application rules.

Examples:

  • Salary calculations

  • Discount calculations

  • Attendance rules

  • Tax computation


Data Access Layer

Responsible only for database communication.


Database

Stores all application data.


Building a DAL Using ADO

The DAL primarily uses ADO objects such as:

  • Connection

  • Command

  • Recordset

  • Parameter

  • Transaction

These objects work together to execute database operations.


Connection Class

A reusable connection class manages database connectivity.

Example:

Public Function OpenConnection()

Dim con As New ADODB.Connection

con.Open ConnectionString

Set OpenConnection = con

End Function

Every module calls this function instead of creating a new connection manually.


Retrieving Records

Example:

Public Function GetEmployees()

Dim rs As New ADODB.Recordset

rs.Open "SELECT * FROM Employees", OpenConnection

Set GetEmployees = rs

End Function

Now every form simply calls:

Set rs = DAL.GetEmployees()

instead of writing SQL repeatedly.


Inserting Records

Example:

Public Sub InsertEmployee(Name As String, Salary As Double)

Dim cmd As New ADODB.Command

cmd.CommandText = "INSERT INTO Employees(Name,Salary) VALUES (?,?)"

End Sub

The insertion logic remains inside the DAL.


Updating Records

Example:

Public Sub UpdateEmployee(ID As Integer, Salary As Double)

UPDATE Employees
SET Salary = Salary
WHERE EmployeeID = ID

End Sub

The application only calls the update function.


Deleting Records

Example:

Public Sub DeleteEmployee(ID As Integer)

DELETE FROM Employees
WHERE EmployeeID = ID

End Sub

Again, the form never interacts directly with SQL.


Using Parameterized Queries

Parameterized queries improve security and prevent SQL injection.

Example:

cmd.CommandText =

"SELECT * FROM Employees WHERE EmployeeID=?"

cmd.Parameters.Append cmd.CreateParameter( , adInteger, adParamInput, , 101)

Instead of concatenating values into SQL strings, parameters safely pass user input.


Using Stored Procedures

The DAL can also execute stored procedures.

Example:

cmd.CommandType = adCmdStoredProc

cmd.CommandText = "GetEmployeeDetails"

Advantages:

  • Faster execution

  • Improved security

  • Easier maintenance

  • Centralized business logic in the database


Transaction Management

Some operations require multiple SQL statements to succeed together.

Example:

Transfer Money

Deduct Balance

Add Balance

Commit Transaction

If one step fails:

Rollback Transaction

The DAL manages transactions to maintain data consistency.


Error Handling

Database errors should be handled inside the DAL.

Example:

On Error GoTo ErrorHandler

...

Exit Sub

ErrorHandler:

MsgBox Err.Description

Centralized error handling keeps the application stable and reduces duplicate error management code.


Reusability

Suppose ten forms need employee information.

Without DAL:

Each form writes:

SELECT * FROM Employees

With DAL:

Every form simply calls:

GetEmployees()

Only one function requires maintenance if the query changes.


Scalability

Suppose the application initially uses Microsoft Access.

Later it migrates to SQL Server.

Without DAL:

Hundreds of SQL statements may require modification.

With DAL:

Only the connection logic and relevant methods in the DAL need updates.

The rest of the application continues to work with little or no change.


Security Benefits

A DAL enhances security by:

  • Hiding database connection details.

  • Restricting direct database access.

  • Using parameterized queries.

  • Executing stored procedures where appropriate.

  • Validating input before executing SQL.

  • Centralizing authentication and authorization checks if needed.


Performance Benefits

A well-designed DAL improves performance by:

  • Reusing database connections where appropriate.

  • Reducing duplicate SQL execution code.

  • Using optimized queries.

  • Supporting transactions.

  • Managing resources efficiently.

  • Reducing unnecessary database requests.


Real-World Applications

Banking Systems

All account operations such as deposits, withdrawals, and balance inquiries use a centralized DAL, ensuring secure and consistent database access.


Hospital Management Systems

Patient registration, doctor schedules, prescriptions, and billing all access the database through the DAL, making maintenance easier.


School Management Systems

Student admissions, attendance, examination results, and fee management use reusable DAL methods for consistent database operations.


Inventory Management Systems

Stock updates, purchase orders, supplier information, and product records are managed through a centralized DAL to ensure accurate and efficient processing.


E-Commerce Applications

Customer registration, product catalogs, shopping carts, order processing, and payment records all interact with the database through the DAL, simplifying maintenance and enhancing security.


Advantages

  • Eliminates duplicate database code.

  • Simplifies application maintenance.

  • Promotes code reusability.

  • Improves security through parameterized queries and centralized access.

  • Enhances application scalability.

  • Supports easier debugging and testing.

  • Encourages separation of concerns between presentation, business logic, and data access.

  • Makes future database migrations easier.

  • Improves consistency across the application.


Limitations

  • Requires careful initial design.

  • Adds an additional layer to the application architecture.

  • Poorly designed DAL methods can become overly complex.

  • Large enterprise applications may require more advanced patterns, such as repositories or object-relational mapping (ORM), in addition to a DAL.


Best Practices

  • Keep all database operations inside the DAL.

  • Use parameterized queries to prevent SQL injection.

  • Reuse connection and command objects efficiently.

  • Handle exceptions within the DAL and provide meaningful error information.

  • Avoid embedding SQL statements in the user interface.

  • Separate business rules from data access logic.

  • Document reusable methods for easier maintenance.

  • Use transactions for operations involving multiple related database changes.

  • Close and dispose of ADO objects properly to free resources.


Conclusion

A reusable ADO Data Access Layer is a key architectural component for building reliable, maintainable, and scalable database applications. By centralizing all database communication, it reduces code duplication, enhances security, simplifies future modifications, and promotes a clear separation between user interface, business logic, and database operations. Whether developing small desktop applications or large enterprise systems, implementing a well-structured DAL with ADO results in cleaner code, easier maintenance, and improved overall application quality.