SlideShare a Scribd company logo
1 of 5
Download to read offline
VB.NET and C# to Microsoft Access using ADO.NET
                                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.
ADO.NET with VB.NET and C#                                                                     Steven Nicolaou

Note for ASP.NET
ASP.NET no longer relies on VBScript, but is instead powered by the .NET framework, which means that it can
be built using VB.NET or C# for example. The source code in this guide will therefore work equally well, whether
you are making a Windows Application, or a Web Application in ASP.NET


ADO.NET
After our brief overview with ADO.NET let’s have a look at how our source code would look. I have provided
examples in both VB.NET and C#. I will be assuming Access as the back-end and will be going through
OLE DB. ADO.NET has a specialised set of classes that are optimised for SQL Server (such as
SqlConnection), but for Access we need to use the regular OLE DB classes.

                                                    VB.NET
      ‘Create the OleDbConnection Object
      ‘DBPath is a fully qualified path to the MDB File
      Private m_Conn As New OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=quot; &
      DBPath)

      ‘To open the Connection we simply call the Open method
      m_Conn.Open()
                                                      C#
      private OleDbConnection m_Conn = New OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;Data
      Source=quot; & DBPath)
      m_Conn.Open();


Now the Connection is open, we have several options, each of which I will demonstrate. Most of these
objectives can work using a DataSet, but the new methods have been provided to make specialised
operations more efficient. For example, the system shouldn’t be made to go through the trouble of building a
complete DataSet in memory, if all we need is a single value.

       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,       Use a Command and call
       such as UPDATE, INSERT, or DELE TE                     ExecuteNonQuery
       Get a Single value from a query, such as “SELECT       Use a Command and call ExecuteScalar
       COUNT(*)”

Get a DataSet that can be used offline
                                                    VB.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, m_Conn)
      m_da.Fill(m_ds) ‘The DataAdapter Fills the DataSet
      m_Conn.Close() ‘Close database Connection
                                                      C#
      DataSet m_ds;
      OleDbDataAdapter m_da = new OleDbDataAdapter(sqltext,m_Conn);
      m_da.Fill(m_ds);
      m_Conn.Close();

The Connection is closed and the DataSet is now filled with data and ready for processing. To better
understand the code below, keep in mind the object hierarchy. A DataSet contains many Tables, which
contain many Rows, which contain Fields.

      DataSet
        L Tables as DataTable
            L Rows as DataRow

The entire DataSet object model has been attached in Appendix A for your convenience.



                                                                                                          Page 2
ADO.NET with VB.NET and C#                                                                        Steven Nicolaou

                                                     VB.NET
      Dim emp As DataRow ‘Single Row in the DataSet
      For Each emp In m_ds.Tables(0).Rows
        EmployeeId = emp(quot;EmployeeIdquot;)
        FirstName = emp(“FirstName”)
        LastName = emp(“LastName”)
        Console.WriteLine(CustomerId,FirstName,LastName) ‘Print out the fields
      Next row
                                                        C#
      foreach(DataRow emp in m_ds.Tables[0].Rows)
      {
        EmployeeId = emp[quot;EmployeeIdquot;];
        FirstName = emp[“FirstName”];
        LastName = emp[“LastName”];
        Console.WriteLine(CustomerId,FirstName,LastName); //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. DataReaders are ideal
for forward -only, read-only operations that don’t require scrolling, such as populating drop down boxes. It is
therefore assumed that we will need it for a short time, and not for repeated reference.

The CommandBehavior.CloseConnection parameter that is sent to the ExecuteReader constructor
forces the Connection to Close as soon as the DataReader is closed.

                                                     VB.NET
      Dim m_cmd As As New OleDbCommand(sqlText, m_Conn)
      Dim dr As OleDbDataReader
      dr = m_cmd.ExecuteReader(CommandBehavior.CloseConnection)
                                                        C#
      private OleDbCommand m_cmd = new OleDbCommand(sqlText, m_Conn);
      private OleDbDataReader dr = m_cmd.ExecuteReader(CommandBehavior.CloseConnection);

To read the records from a DataReader, we need to call the Read method and simply retrieve the fields by
name. We keep calling until Read returns False, at which point we have read all records.

                                                     VB.NET
      While dr.Read()
        EmployeeId = dr(quot;EmployeeIdquot;)
        FirstName = dr(quot;FirstNamequot;)
        LastName = dr(quot;LastNamequot;)
        Console.WriteLine(CustomerId,FirstName,LastName) ‘Print out the fields
      End While
      dr.Close() ‘Close the DataReader and release the Connection
                                                        C#
      while (dr.Read())
      {
        EmployeeId = dr[quot;EmployeeIdquot;];
        FirstName = dr[quot;FirstNamequot;];
        LastName = dr[quot;LastNamequot;];
        Console.WriteLine(CustomerId,FirstName,LastName); //Print out the fields
      }
      dr.Close(); //Close the DataReader and release the Connection




                                                                                                             Page 3
ADO.NET with VB.NET and C#                                                                Steven Nicolaou

Perform operations that do not return a DataSet, such as UPDATE,
INSERT or DELETE
After creating a command object, we need to call the ExecuteNonQuery method. We can optionally get the
number of rows affected by the operation by examining its return value, as in the example.

                                                 VB.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, 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, m_Conn)
     RowsAffected = cmd.ExecuteNonQuery()
     m_Conn.Close() ‘Don’t forget to close the Connection immediately afterwards
                                                    C#
     private String sqlText = “DELETE * FROM EMPLOYEES WHERE EMPLOYEE_ID = 5”;
     private OleDbCommand cmd = new OleDbCommand(sqlText, m_Conn);
     int RowsAffected = cmd.ExecuteNonQuery();
     m_Conn.Close(); //Don’t forget to close the Connection immediately afterwards




Get a Single value from a query, such as SELECT COUNT (*)
There is a special method called ExecuteScalar specifically optimised for queries that return single
values. Although a DataSet could be used, ExecuteScalar will be much more efficient. The following
example assumes the returned value is an Integer.

                                                 VB.NET
     Dim retItem As Integer
     Dim cmd As New OleDbCommand(sqlText, m_Conn)
     retItem = cmd.ExecuteScalar()
     m_Conn.Close()
                                                    C#
     int retItem;
     private OleDbCommand cmd = new OleDbCommand(sqlText, m_Conn);
     retItem = cmd.ExecuteScalar();
     m_Conn.Close();




More Information
For more information on ADO.NET and examples using SQL Server visit the MSDN
http://msdn.microsoft.com/libr ary/default.asp?url=/library/en-us/Dndotnet/html/Usingadonet.asp




                                                                                                     Page 4
ADO.NET with VB.NET and C#                                                                    Steven Nicolaou

Appendix A: DataSet Object Model




The DataTableCollection
An ADO.NET DataSet contains a collection of zero or more tables represented by DataTable objects. The
DataTableCollection contains all the DataTable objects in a DataSet .


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




                                                                                                         Page 5

More Related Content

What's hot

Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml datakendyhuu
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetFaRid Adwa
 
Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Mubarak Hussain
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NETrchakra
 
Ado.net & data persistence frameworks
Ado.net & data persistence frameworksAdo.net & data persistence frameworks
Ado.net & data persistence frameworksLuis Goldster
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentalsMadhuri Kavade
 
Dealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETDealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETFernando G. Guerrero
 
Disconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETDisconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETEverywhere
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.netHemant Sankhla
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationRandy Connolly
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12Sisir Ghosh
 

What's hot (20)

ADO.NET
ADO.NETADO.NET
ADO.NET
 
Ado.net
Ado.netAdo.net
Ado.net
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml data
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.Net
 
Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Ado dot net complete meterial (1)
Ado dot net complete meterial (1)
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
Ado.net & data persistence frameworks
Ado.net & data persistence frameworksAdo.net & data persistence frameworks
Ado.net & data persistence frameworks
 
Ado.net
Ado.netAdo.net
Ado.net
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
For Beginers - ADO.Net
For Beginers - ADO.NetFor Beginers - ADO.Net
For Beginers - ADO.Net
 
Simple Data Binding
Simple Data BindingSimple Data Binding
Simple Data Binding
 
Dealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETDealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NET
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
Disconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETDisconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NET
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.net
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 

Viewers also liked

Share point 2010-uiimprovements
Share point 2010-uiimprovementsShare point 2010-uiimprovements
Share point 2010-uiimprovementsLiquidHub
 
Share point 2013
Share point 2013Share point 2013
Share point 2013LiquidHub
 
Sharepoint 2013 upgrade process
Sharepoint 2013 upgrade processSharepoint 2013 upgrade process
Sharepoint 2013 upgrade processLiquidHub
 
Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0LiquidHub
 
Database programming in vb net
Database programming in vb netDatabase programming in vb net
Database programming in vb netZishan yousaf
 

Viewers also liked (6)

Share point 2010-uiimprovements
Share point 2010-uiimprovementsShare point 2010-uiimprovements
Share point 2010-uiimprovements
 
Share point 2013
Share point 2013Share point 2013
Share point 2013
 
Sharepoint 2013 upgrade process
Sharepoint 2013 upgrade processSharepoint 2013 upgrade process
Sharepoint 2013 upgrade process
 
Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0
 
Database programming in vb net
Database programming in vb netDatabase programming in vb net
Database programming in vb net
 
Database Connection
Database ConnectionDatabase Connection
Database Connection
 

Similar to Ado.Net

Similar to Ado.Net (20)

Asp.Net Database
Asp.Net DatabaseAsp.Net Database
Asp.Net Database
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
unit 3.docx
unit 3.docxunit 3.docx
unit 3.docx
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to ado
 
Unit4
Unit4Unit4
Unit4
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net Architecture
 
Jdbc
JdbcJdbc
Jdbc
 
Ado
AdoAdo
Ado
 
Ado.net
Ado.netAdo.net
Ado.net
 
Csharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxCsharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptx
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Bt0082 visual basic2
Bt0082 visual basic2Bt0082 visual basic2
Bt0082 visual basic2
 
2310 b 10
2310 b 102310 b 10
2310 b 10
 
Ss dotnetcodexmpl
Ss dotnetcodexmplSs dotnetcodexmpl
Ss dotnetcodexmpl
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
Marmagna desai
Marmagna desaiMarmagna desai
Marmagna desai
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
 
B_110500002
B_110500002B_110500002
B_110500002
 
Ado.net by Awais Majeed
Ado.net by Awais MajeedAdo.net by Awais Majeed
Ado.net by Awais Majeed
 

More from LiquidHub

Microsoft office-sharepoint-server-2007-presentation-120211522467022-2
Microsoft office-sharepoint-server-2007-presentation-120211522467022-2Microsoft office-sharepoint-server-2007-presentation-120211522467022-2
Microsoft office-sharepoint-server-2007-presentation-120211522467022-2LiquidHub
 
Managing metadata in_share_point_2010
Managing metadata in_share_point_2010Managing metadata in_share_point_2010
Managing metadata in_share_point_2010LiquidHub
 
Fast search for share point
Fast search for share pointFast search for share point
Fast search for share pointLiquidHub
 
Simple Farm Server Deployment
Simple Farm Server DeploymentSimple Farm Server Deployment
Simple Farm Server DeploymentLiquidHub
 
Pre Install Databases
Pre Install DatabasesPre Install Databases
Pre Install DatabasesLiquidHub
 
Moss 2007 Deployment Detail
Moss 2007 Deployment DetailMoss 2007 Deployment Detail
Moss 2007 Deployment DetailLiquidHub
 
Moss 2007 Backup Strategies
Moss 2007 Backup StrategiesMoss 2007 Backup Strategies
Moss 2007 Backup StrategiesLiquidHub
 
How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003
How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003
How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003LiquidHub
 
5060 A 01 Demonstration Steps
5060 A 01 Demonstration Steps5060 A 01 Demonstration Steps
5060 A 01 Demonstration StepsLiquidHub
 
Working With Infopath 2007
Working With Infopath 2007Working With Infopath 2007
Working With Infopath 2007LiquidHub
 
Whats New In Microsoft Windows Share Point Services Feature Walkthrough
Whats New In Microsoft Windows Share Point Services Feature WalkthroughWhats New In Microsoft Windows Share Point Services Feature Walkthrough
Whats New In Microsoft Windows Share Point Services Feature WalkthroughLiquidHub
 
Overviewofthe2007 Microsoft Office System Components Refresh
Overviewofthe2007 Microsoft Office System Components RefreshOverviewofthe2007 Microsoft Office System Components Refresh
Overviewofthe2007 Microsoft Office System Components RefreshLiquidHub
 
Organizingand Finding Resourceswith Office Share Point Server2007 Refresh
Organizingand Finding Resourceswith Office Share Point Server2007 RefreshOrganizingand Finding Resourceswith Office Share Point Server2007 Refresh
Organizingand Finding Resourceswith Office Share Point Server2007 RefreshLiquidHub
 
Organizingand Finding Resourceswith Office Share Point Server2007
Organizingand Finding Resourceswith Office Share Point Server2007Organizingand Finding Resourceswith Office Share Point Server2007
Organizingand Finding Resourceswith Office Share Point Server2007LiquidHub
 
Office Share Point Server2007 Functionaland Architectural Overview
Office Share Point Server2007 Functionaland Architectural OverviewOffice Share Point Server2007 Functionaland Architectural Overview
Office Share Point Server2007 Functionaland Architectural OverviewLiquidHub
 
Office2007 Overview Express
Office2007 Overview ExpressOffice2007 Overview Express
Office2007 Overview ExpressLiquidHub
 
Moss2007 Installation Configuration
Moss2007 Installation ConfigurationMoss2007 Installation Configuration
Moss2007 Installation ConfigurationLiquidHub
 

More from LiquidHub (20)

Microsoft office-sharepoint-server-2007-presentation-120211522467022-2
Microsoft office-sharepoint-server-2007-presentation-120211522467022-2Microsoft office-sharepoint-server-2007-presentation-120211522467022-2
Microsoft office-sharepoint-server-2007-presentation-120211522467022-2
 
Managing metadata in_share_point_2010
Managing metadata in_share_point_2010Managing metadata in_share_point_2010
Managing metadata in_share_point_2010
 
Fast search for share point
Fast search for share pointFast search for share point
Fast search for share point
 
Simple Farm Server Deployment
Simple Farm Server DeploymentSimple Farm Server Deployment
Simple Farm Server Deployment
 
Pre Install Databases
Pre Install DatabasesPre Install Databases
Pre Install Databases
 
Moss 2007 Deployment Detail
Moss 2007 Deployment DetailMoss 2007 Deployment Detail
Moss 2007 Deployment Detail
 
Moss 2007 Backup Strategies
Moss 2007 Backup StrategiesMoss 2007 Backup Strategies
Moss 2007 Backup Strategies
 
How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003
How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003
How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003
 
Bdc Screens
Bdc ScreensBdc Screens
Bdc Screens
 
Bdc Screens
Bdc ScreensBdc Screens
Bdc Screens
 
5060 A 01 Demonstration Steps
5060 A 01 Demonstration Steps5060 A 01 Demonstration Steps
5060 A 01 Demonstration Steps
 
5060 A 01
5060 A 015060 A 01
5060 A 01
 
Working With Infopath 2007
Working With Infopath 2007Working With Infopath 2007
Working With Infopath 2007
 
Whats New In Microsoft Windows Share Point Services Feature Walkthrough
Whats New In Microsoft Windows Share Point Services Feature WalkthroughWhats New In Microsoft Windows Share Point Services Feature Walkthrough
Whats New In Microsoft Windows Share Point Services Feature Walkthrough
 
Overviewofthe2007 Microsoft Office System Components Refresh
Overviewofthe2007 Microsoft Office System Components RefreshOverviewofthe2007 Microsoft Office System Components Refresh
Overviewofthe2007 Microsoft Office System Components Refresh
 
Organizingand Finding Resourceswith Office Share Point Server2007 Refresh
Organizingand Finding Resourceswith Office Share Point Server2007 RefreshOrganizingand Finding Resourceswith Office Share Point Server2007 Refresh
Organizingand Finding Resourceswith Office Share Point Server2007 Refresh
 
Organizingand Finding Resourceswith Office Share Point Server2007
Organizingand Finding Resourceswith Office Share Point Server2007Organizingand Finding Resourceswith Office Share Point Server2007
Organizingand Finding Resourceswith Office Share Point Server2007
 
Office Share Point Server2007 Functionaland Architectural Overview
Office Share Point Server2007 Functionaland Architectural OverviewOffice Share Point Server2007 Functionaland Architectural Overview
Office Share Point Server2007 Functionaland Architectural Overview
 
Office2007 Overview Express
Office2007 Overview ExpressOffice2007 Overview Express
Office2007 Overview Express
 
Moss2007 Installation Configuration
Moss2007 Installation ConfigurationMoss2007 Installation Configuration
Moss2007 Installation Configuration
 

Recently uploaded

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Recently uploaded (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

Ado.Net

  • 1. VB.NET and C# to Microsoft Access using ADO.NET 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.
  • 2. ADO.NET with VB.NET and C# Steven Nicolaou Note for ASP.NET ASP.NET no longer relies on VBScript, but is instead powered by the .NET framework, which means that it can be built using VB.NET or C# for example. The source code in this guide will therefore work equally well, whether you are making a Windows Application, or a Web Application in ASP.NET ADO.NET After our brief overview with ADO.NET let’s have a look at how our source code would look. I have provided examples in both VB.NET and C#. I will be assuming Access as the back-end and will be going through OLE DB. ADO.NET has a specialised set of classes that are optimised for SQL Server (such as SqlConnection), but for Access we need to use the regular OLE DB classes. VB.NET ‘Create the OleDbConnection Object ‘DBPath is a fully qualified path to the MDB File Private m_Conn As New OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=quot; & DBPath) ‘To open the Connection we simply call the Open method m_Conn.Open() C# private OleDbConnection m_Conn = New OleDbConnection(quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=quot; & DBPath) m_Conn.Open(); Now the Connection is open, we have several options, each of which I will demonstrate. Most of these objectives can work using a DataSet, but the new methods have been provided to make specialised operations more efficient. For example, the system shouldn’t be made to go through the trouble of building a complete DataSet in memory, if all we need is a single value. 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, Use a Command and call such as UPDATE, INSERT, or DELE TE ExecuteNonQuery Get a Single value from a query, such as “SELECT Use a Command and call ExecuteScalar COUNT(*)” Get a DataSet that can be used offline VB.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, m_Conn) m_da.Fill(m_ds) ‘The DataAdapter Fills the DataSet m_Conn.Close() ‘Close database Connection C# DataSet m_ds; OleDbDataAdapter m_da = new OleDbDataAdapter(sqltext,m_Conn); m_da.Fill(m_ds); m_Conn.Close(); The Connection is closed and the DataSet is now filled with data and ready for processing. To better understand the code below, keep in mind the object hierarchy. A DataSet contains many Tables, which contain many Rows, which contain Fields. DataSet L Tables as DataTable L Rows as DataRow The entire DataSet object model has been attached in Appendix A for your convenience. Page 2
  • 3. ADO.NET with VB.NET and C# Steven Nicolaou VB.NET Dim emp As DataRow ‘Single Row in the DataSet For Each emp In m_ds.Tables(0).Rows EmployeeId = emp(quot;EmployeeIdquot;) FirstName = emp(“FirstName”) LastName = emp(“LastName”) Console.WriteLine(CustomerId,FirstName,LastName) ‘Print out the fields Next row C# foreach(DataRow emp in m_ds.Tables[0].Rows) { EmployeeId = emp[quot;EmployeeIdquot;]; FirstName = emp[“FirstName”]; LastName = emp[“LastName”]; Console.WriteLine(CustomerId,FirstName,LastName); //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. DataReaders are ideal for forward -only, read-only operations that don’t require scrolling, such as populating drop down boxes. It is therefore assumed that we will need it for a short time, and not for repeated reference. The CommandBehavior.CloseConnection parameter that is sent to the ExecuteReader constructor forces the Connection to Close as soon as the DataReader is closed. VB.NET Dim m_cmd As As New OleDbCommand(sqlText, m_Conn) Dim dr As OleDbDataReader dr = m_cmd.ExecuteReader(CommandBehavior.CloseConnection) C# private OleDbCommand m_cmd = new OleDbCommand(sqlText, m_Conn); private OleDbDataReader dr = m_cmd.ExecuteReader(CommandBehavior.CloseConnection); To read the records from a DataReader, we need to call the Read method and simply retrieve the fields by name. We keep calling until Read returns False, at which point we have read all records. VB.NET While dr.Read() EmployeeId = dr(quot;EmployeeIdquot;) FirstName = dr(quot;FirstNamequot;) LastName = dr(quot;LastNamequot;) Console.WriteLine(CustomerId,FirstName,LastName) ‘Print out the fields End While dr.Close() ‘Close the DataReader and release the Connection C# while (dr.Read()) { EmployeeId = dr[quot;EmployeeIdquot;]; FirstName = dr[quot;FirstNamequot;]; LastName = dr[quot;LastNamequot;]; Console.WriteLine(CustomerId,FirstName,LastName); //Print out the fields } dr.Close(); //Close the DataReader and release the Connection Page 3
  • 4. ADO.NET with VB.NET and C# Steven Nicolaou Perform operations that do not return a DataSet, such as UPDATE, INSERT or DELETE After creating a command object, we need to call the ExecuteNonQuery method. We can optionally get the number of rows affected by the operation by examining its return value, as in the example. VB.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, 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, m_Conn) RowsAffected = cmd.ExecuteNonQuery() m_Conn.Close() ‘Don’t forget to close the Connection immediately afterwards C# private String sqlText = “DELETE * FROM EMPLOYEES WHERE EMPLOYEE_ID = 5”; private OleDbCommand cmd = new OleDbCommand(sqlText, m_Conn); int RowsAffected = cmd.ExecuteNonQuery(); m_Conn.Close(); //Don’t forget to close the Connection immediately afterwards Get a Single value from a query, such as SELECT COUNT (*) There is a special method called ExecuteScalar specifically optimised for queries that return single values. Although a DataSet could be used, ExecuteScalar will be much more efficient. The following example assumes the returned value is an Integer. VB.NET Dim retItem As Integer Dim cmd As New OleDbCommand(sqlText, m_Conn) retItem = cmd.ExecuteScalar() m_Conn.Close() C# int retItem; private OleDbCommand cmd = new OleDbCommand(sqlText, m_Conn); retItem = cmd.ExecuteScalar(); m_Conn.Close(); More Information For more information on ADO.NET and examples using SQL Server visit the MSDN http://msdn.microsoft.com/libr ary/default.asp?url=/library/en-us/Dndotnet/html/Usingadonet.asp Page 4
  • 5. ADO.NET with VB.NET and C# Steven Nicolaou Appendix A: DataSet Object Model The DataTableCollection An ADO.NET DataSet contains a collection of zero or more tables represented by DataTable objects. The DataTableCollection contains all the DataTable objects in a DataSet . The DataRelationCollection A DataSet contains relationships in its DataRelationCollection object. A relationship, represented by the DataRelation object, associates rows in one DataTable with rows in another DataTable. It is analogous to a join path that might exist between primary and foreign key columns in a relational database. A DataRelation identifies matching columns in two tables of a DataSet. Relationships enable navigation from one table to another within a DataSet. The essential elements of a DataRelation are the name of the relationship, the name of the tables being related, and the related columns in each table. Relationships can be built with more than one column per table by specifying an array of DataColumn objects as the key columns. When a relationship is added to the DataRelationCollection, it may optionally add a UniqueKeyConstraint and a ForeignKeyConstraint to enforce integrity constraints when changes are made to related column values. Page 5