You are on page 1of 5

VB.NET and C# to Microsoft Access using ADO.

by Steven Nicolaou
Microsoft Certified Solution Developer
Microsoft Certified Professional SQL Server, Visual Basic Desktop & Distributed

Introduction to ADO.NET
For those of you familiar with ActiveX Data Objects (ADO) in Visual Basic, you will be well aware of the concept of
the Connection, the Command and the Recordset. These are the primary classes that constitute ADO’s data
access technology. In the .NET framework, ADO has been through major reengineering and has been renamed
to ADO.NET to reflect its position as the underlying data framework for .NET. Here is a quick overview.

The new Object Model in ADO.NET

The Connection and Command are still there, but the Recordset has been replaced by the DataSet and we have
a new Object called a DataAdapter , which is a toolset that handles processing between a Command and a
Connection . There is also a new Object called a DataReader, which is essentially what would have been a Read-
Only Forward -Only Cursor Records et in ADO and is the most efficient way to get data.

You will notice that the DataSet has a DataTable collection, which reveals its ability to hold resultsets from more
than one table, a big improvement over ADO Recordsets. Moreover, the tables can be related through
Relationship objects, which allow the programmer to perform joins without going back to the database. In addition
to table relationships, ADO.NET is aware of Primary Key, Foreign Key and Unique constraints, as well as
Autonumber (IDENTITY/SEQUENCE) fields.

A very popular way of working with data in VB and ADO was to keep the connection open, while making changes
directly to the database. ADO.NET encourages greater use of the disconnected model. The programmer should
keep a connection to the database open for as little as possible. This improves scalability and makes more sense
in a web-enabled system. The process of retrieving and updating data should be as follows:

1. Open Connection
2. Get DataSet
3. Close Connection
4. Perform Operations on the DataSet

When you are ready to commit the changes back to the database:

5. Open Connection
6. Submit Changes from DataSet
7. Close Connection

And so on.

In the diagram above, Connected Objects are the ones that are normally used while the Connection to the
database is open and Disconnected Objects are the ones that can be used once the connection is closed.

Data Source=" & DBPath) ‘To open the Connection we simply call the Open method m_Conn.NET let’s have a look at how our source code would look. whether you are making a Windows Application.NET with VB. VB.Jet.OLEDB. but the new methods have been provided to make specialised operations more efficient.NET ‘Create the OleDbConnection Object ‘DBPath is a fully qualified path to the MDB File Private m_Conn As New OleDbConnection("Provider=Microsoft. or DELE TE ExecuteNonQuery Get a Single value from a query. keep in mind the object hierarchy.NET and C#. ADO. but for Access we need to use the regular OLE DB classes.NET has a specialised set of classes that are optimised for SQL Server (such as SqlConnection). which contain Fields. Most of these objectives can work using a DataSet.Close() ‘Close database Connection C# DataSet m_ds. Now the Connection is open.Open(). if all we need is a single value. To better understand the code below.Fill(m_ds) ‘The DataAdapter Fills the DataSet m_Conn.0. each of which I will demonstrate.m_Conn). the system shouldn’t be made to go through the trouble of building a complete DataSet in memory.4.NET framework.4. m_da.NET After our brief overview with ADO. OleDbDataAdapter m_da = new OleDbDataAdapter(sqltext.ADO. which contain many Rows.Data Source=" & DBPath) m_Conn.NET no longer relies on VBScript. but is instead powered by the . m_Conn) m_da. or a Web Application in ASP.NET ASP. Use a Command and call such as UPDATE. INSERT.Open() C# private OleDbConnection m_Conn = New OleDbConnection("Provider=Microsoft. DataSet L Tables as DataTable L Rows as DataRow The entire DataSet object model has been attached in Appendix A for your convenience.Close().OLEDB.NET or C# for example. we have several options. I have provided examples in both VB. I will be assuming Access as the back-end and will be going through OLE DB.Jet. For example. The source code in this guide will therefore work equally well. A DataSet contains many Tables. which means that it can be built using VB. Page 2 .NET ‘The DataAdapter Constructor takes 2 parameters in this case: The SQL Text and the Connection Object Dim m_ds as DataSet Dim m_da = New OleDbDataAdapter(sqltext.Fill(m_ds). Objective Action Get a DataSet that can be used offline Use a DataAdapter and call Fill Get a DataReader (can only be used online) Use a Command and call ExecuteReader Perform a non-DataSet operation on the Database. The Connection is closed and the DataSet is now filled with data and ready for processing. m_Conn.NET ADO.0. such as “SELECT Use a Command and call ExecuteScalar COUNT(*)” Get a DataSet that can be used offline VB.NET and C# Steven Nicolaou Note for ASP.

ExecuteReader(CommandBehavior.CloseConnection).ADO.CloseConnection) C# private OleDbCommand m_cmd = new OleDbCommand(sqlText. We keep calling until Read returns False.Read()) { EmployeeId = dr["EmployeeId"]. //Print out the fields } Get a DataReader (can only be used online) The one gotcha of DataReaders is that they need the connection to be open to work.FirstName. FirstName = dr["FirstName"]. such as populating drop down boxes.CloseConnection parameter that is sent to the ExecuteReader constructor forces the Connection to Close as soon as the DataReader is closed. at which point we have read all records.FirstName.Read() EmployeeId = dr("EmployeeId") FirstName = dr("FirstName") LastName = dr("LastName") Console.WriteLine(CustomerId.Tables(0).WriteLine(CustomerId. VB. To read the records from a DataReader.LastName).WriteLine(CustomerId.NET with VB. m_Conn). //Close the DataReader and release the Connection Page 3 . we need to call the Read method and simply retrieve the fields by name.LastName) ‘Print out the fields Next row C# foreach(DataRow emp in m_ds.NET Dim emp As DataRow ‘Single Row in the DataSet For Each emp In m_ds. //Print out the fields } dr. LastName = dr["LastName"]. private OleDbDataReader dr = m_cmd. It is therefore assumed that we will need it for a short time.FirstName. and not for repeated reference.NET Dim m_cmd As As New OleDbCommand(sqlText.LastName). DataReaders are ideal for forward -only. read-only operations that don’t require scrolling. Console.Close() ‘Close the DataReader and release the Connection C# while (dr.Rows) { EmployeeId = emp["EmployeeId"].Close(). Console.Tables[0]. FirstName = emp[“FirstName”].LastName) ‘Print out the fields End While dr. LastName = emp[“LastName”].Rows EmployeeId = emp("EmployeeId") FirstName = emp(“FirstName”) LastName = emp(“LastName”) Console.WriteLine(CustomerId. m_Conn) Dim dr As OleDbDataReader dr = m_cmd. VB.FirstName.ExecuteReader(CommandBehavior. The CommandBehavior.NET While dr.NET and C# Steven Nicolaou VB.

VB.NET with VB.ExecuteScalar() m_Conn. such as SELECT COUNT (*) There is a special method called ExecuteScalar specifically optimised for queries that return single values. //Don’t forget to close the Connection immediately afterwards Get a Single value from a m_Conn. and the Connection Object Dim sqlText as String = “DELETE * FROM EMPLOYEES WHERE EMPLOYEE_ID = 5” Dim RowsAffected as Integer Dim cmd As New OleDbCommand(sqlText.Close(). The following example assumes the returned value is an Integer. m_Conn) RowsAffected = cmd. such as UPDATE. as in the example. private OleDbCommand cmd = new OleDbCommand(sqlText. m_Conn).asp Page 4 . ary/default. Although a DataSet could be used. More Information For more information on ADO. int RowsAffected = cmd.ExecuteScalar().asp?url=/library/en-us/Dndotnet/html/Usingadonet.NET and C# Steven Nicolaou Perform operations that do not return a DataSet. we need to call the ExecuteNonQuery method.NET ‘Now we need to make a Command that we’ll use to send the query ‘The OleDBCommand Constructor takes 2 parameters in this case: The SQL Text. m_Conn.Close() ‘Don’t forget to close the Connection immediately afterwards C# private String sqlText = “DELETE * FROM EMPLOYEES WHERE EMPLOYEE_ID = 5”.Close(). INSERT or DELETE After creating a command object. VB.NET Dim retItem As Integer Dim cmd As New OleDbCommand(sqlText. m_Conn) retItem = cmd. m_Conn).Close() C# int retItem.ADO.NET and examples using SQL Server visit the MSDN http://msdn. We can optionally get the number of rows affected by the operation by examining its return value. retItem = cmd. ExecuteScalar will be much more efficient.ExecuteNonQuery(). private OleDbCommand cmd = new OleDbCommand(sqlText.

the name of the tables being related. it may optionally add a UniqueKeyConstraint and a ForeignKeyConstraint to enforce integrity constraints when changes are made to related column values. Relationships can be built with more than one column per table by specifying an array of DataColumn objects as the key columns. represented by the DataRelation object. Relationships enable navigation from one table to another within a DataSet. It is analogous to a join path that might exist between primary and foreign key columns in a relational database. A relationship. The DataRelationCollection A DataSet contains relationships in its DataRelationCollection object. The essential elements of a DataRelation are the name of the relationship. associates rows in one DataTable with rows in another DataTable. A DataRelation identifies matching columns in two tables of a DataSet.NET with VB. The DataTableCollection contains all the DataTable objects in a DataSet . When a relationship is added to the DataRelationCollection. Page 5 .ADO.NET DataSet contains a collection of zero or more tables represented by DataTable objects.NET and C# Steven Nicolaou Appendix A: DataSet Object Model The DataTableCollection An ADO. and the related columns in each table.