introducing ado

Upload: jay-desai

Post on 09-Apr-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Introducing ADO

    1/7

    Introducing ADO.NET

    Most of today's applications need to interact with database systems to persist, edit or view data.In .NET, data access services are provided through ADO.NET components. ADO.NET is an

    object oriented framework that allows you to interact with database systems. We usually

    interact with database systems through SQL queries or stored procedures. The best thing aboutADO.NET is that it is extremely flexible and efficient. ADO.NET also introduces the concept ofdisconnected data architecture. In traditional data access components, you made a connectionto the database system and then interacted with it through SQL queries using the connection.The application stays connected to the DB system even when it is not using DB services. Thiscommonly wastes valuable and expensive database resources, as most of the time applicationsonly query and view the persistent data. ADO.NET solves this problem by managing a localbuffer of persistent data called a data set. Your application automatically connects to thedatabase serverwhen it needs to run a query and then disconnects immediately after gettingthe result back and storing it in the dataset. This design of ADO.NET is called disconnected dataarchitecture and is very much similar to the connectionless services of HTTP on the internet. Itshould be noted that ADO.NET also provides connection oriented traditional data access

    services.

    Traditional Data Access Architecture

    http://www.programmersheaven.com/articles/faraz/lesson13_img1.jpg

    ADO.NET Disconnected Data Access Architecture

    http://www.programmersheaven.com/articles/faraz/lesson13_img2.jpgAnother important aspect of disconnected architecture is that it maintains a local repository ofdata in the dataset object. The dataset object stores the tables, their relationships and theirdifferent constraints. The user can perform operations like update, insert and delete on this

    local dataset. The changes made to the dataset are applied to the actual database as a batchwhen needed. This greatly reduces network traffic and results in better performance.

    Different components of ADO.NET

    Before going into the details of implementing data access applications using ADO.NET, it isimportant to understand its different supporting components or classes. All of the genericclasses for data access are contained in the System.Data namespace.

    Class Description

    DataSet The DataSet is a local buffer of tables or a collection of disconnected recordsetsDataTable A DataTable is used to contain data in tabular form using rows and columns.

    DataRow Represents a single record or row in a DataTable

    DataColumn Represents a column or field of a DataTable

    DataRelation Represents the relationship between different tables in a DataSet.

    Constraint Represents the constraints or limitations that apply to a particular field or column.

  • 8/8/2019 Introducing ADO

    2/7

    ADO.NET also contains some database specific classes. This means that different databasesystem providers may provide classes (ordrivers) optimized for their particular databasesystem. Microsoft itself has provided the specialized and optimized classes for their SQL server

    database system. The names of these classes start with 'Sql' and are contained in the

    System.Data.SqlClient namespace. Similarly, Oracle has also provides its classes (drivers)optimized for the Oracle DB System. Microsoft has also provided the general classes which canconnect your application to any OLE supported database server. The name of these classesstart with 'OleDb' and these are contained in the System.Data.OleDb namespace. In fact, youcan use OleDb classes to connect to SQL server or Oracle database; using the databasespecific classes generally provides optimized performance however.

    Class Description

    SqlConnection, OleDbConnection Represents a connection to the database system

    SqlCommand, OleDbCommand Represents SQL a query

    SqlDataAdapter, OleDbDataAdapter A class that connects to the database system, fetches the reco

    SqlDataReader, OleDbDataReader A stream that reads data from the database in a connected de

    SqlParameter, OleDbParameter Represents a parameter to a stored procedure

    A review of basic SQL queries

    Here we present a brief review of four basic SQL queries.

    SQL SELECT Statement

    This query is used to select certain columns of certain records from one or more databasetables.

    SELECT * from emp

    selects all the fields of all the records from the table named 'emp'

    SELECT empno, ename from emp

    selects the fields empno and ename for all of the records from the table named 'emp'

    SELECT * from emp where empno< 100

    selects all records from the table named 'emp' where the value of the field empno is less than

    100

    SELECT * from article, author where article.authorId =author.authorId

    selects all records from the tables named 'article' and 'author' that have the same value of thefield authorId

    SQL INSERT Statement

  • 8/8/2019 Introducing ADO

    3/7

    This query is used to insert a record into a database table.

    INSERT INTO emp(empno, ename) values(101, 'John Gut tag')

    inserts a record in to the emp table and sets its empno field to 101 and its ename field to 'JohnGuttag'

    SQL UPDATE StatementThis query is used to modify existing records in a database table.

    UPDATE emp SET ename = 'Eric Gamma' WHERE empno = 1 01

    updates the record whose empno field is 101 by setting its ename field to 'Eric Gamma'

    SQL DELETE StatementThis query is used to delete existing record(s) from a database table.

    DELETE FROM emp WHERE empno = 101deletes the record whose empno field is 101 from the emp table

    y Note that its not good practice to allow users to actually delete records from yourdatabase. This is open to abuse an human error. A more safer method is to flag a fieldwith an end date. I.eWhen a user "deletes" a record, what really happens is this.

    UPDATE emp SET enddate = GetNow(date) WHERE empno = 101

    To remove this record from the users reach in future quieries.

    Select * FROM emp WHERE enddate = Null

    Performing common data access tasks with ADO.NET

    Enough review and introduction! Let's start something practical. Now we will build anapplication to demonstrate how common data access tasks are performed using ADO.NET.

    We will use MS SQL server and MS Access database systems to perform the data access tasks.SQL Server is used because probably most of the time you will be using MS SQL serverwhen

    developing .NET applications (And theres a free cut down version available from Microsoft). ForSQL server, we will be using classes from the System.Data.SqlClient namespace. Access isused to demonstrate the OleDb databases. For Access we will be using classes from the

    System.Data.OleDb namespace. In fact, there is nothing different in these two approaches fordevelopers and only two or three statements will be different in both cases. We will highlight thespecific statements for these two using comments like:

    ' For SQL server

  • 8/8/2019 Introducing ADO

    4/7

    Dim dataAdapter As New SqlDataAdapter(commandString, conn)' For AccessDim dataAdapter As New OleDbDataAdapter(commandString, conn)

    For the example code, we will be using a database named 'ProgrammersHeaven'. The databasewill have a table named 'Article'. The fields of the table 'Article' are

    Field Name Type Description

    artId (Primary Key)Integer The unique identifier for an article

    title String The title of an article

    topic String Topic or Series name of the article like 'Multithreading in

    authorId (Foreign Key)Integer Unique identity of author

    lines Integer Number of lines in the article

    dateOfPublishing Date The date the article was published

    The 'ProgrammersHeaven' database also contains a table named 'Author' with the followingfields:

    Field Name Type

    authorId (Primary Key)Integer The unique identity of the aut

    name String Name of the author

    Accessing Data using ADO.NETData access using ADO.NET involves the following steps:

    y Defining the connection string for the database servery Defining the connection (SqlConnection or OleDbConnection) to the database using a

    connection stringy Defining the command (SqlCommand or OleDbCommand) or command string that

    contains the queryy Defining the Data Adapter (SqlDataAdapter or OleDbDataAdapter) using the command

    string and the connection objecty Creating a new DataSet objecty If the SQL command is SELECT, filling the DataSet object with the results of the query

    through the Data Adaptery Reading the records from the DataTables in the DataSets using the DataRow and

    DataColumn objectsy If the SQL command is UPDATE, INSERT or DELETE. The dataset will be updated

    through the data adaptery Accepting to save the changes in the DataSet to the database

    Since we are demonstrating an application that uses both SQL Server and Access databases we

    need to include the following namespaces in our application:

  • 8/8/2019 Introducing ADO

    5/7

    Imports System.DataImportsSystem.Data.OleDb ' for Acces sdatabaseImports System.Data.SqlClient ' for SQL Server

    Let's now discuss each of the above steps individually

    Defining the connection string

    The connection string defines which database server you are using, where it resides, your username and password and optionally the database name.

    For SQL Server we have written the following connection string:

    ' forSql ServerDim connectionString As String = "server=P-III;database=programmersheaven;" + _"uid=phuser; pwd=nicecoding;"

    First of all we have defined the instance name of the server, which is "P-III" on our system. Nextwe defined the name of the database, the user id (uid) and the password (pwd). These days

    when you install Sql server the installation forces you to think of a password f or the SA (SystemAdministrator) user .Its good practice for you to create another admin user and not use the SAuser ever again. This will help stop intruders breaking in to your database.

    For Access, we have written the following connection string:

    ' for MS AccessDim connectionString As String ="provider=Microsoft.Jet.OLEDB.4.0;" + _"data source = c:\programmersheaven.mdb"

    We have defined the provider of the access database. Then we have defined the data source

    which is the location of the target d atabase.

    Author's Note: Connection string details are vendor specific. A good source of connectionstrings for different databases is http://www.connectionstrings.com

    Defining a ConnectionA connection is defined using the connection string. This object is used by the Data Adapter to

    connect to and disconnect from the database. For SQL Server, a connection is created like this:

    ' forSql ServerDim conn As New SqlConnection(connectionString)

    And for Access, a connection is created like this:

    ' for MS AccessDim conn As New OleDbConnection(connectionString)

  • 8/8/2019 Introducing ADO

    6/7

    Here we have passed the connection string to the constructor of the connection object.

    Defining the command or command stringThe command contains the query to be passed to the database. We are using a commandstring. We will see the command object (SqlCommand or OleDbCommand) later in the lesson.

    The command string we have used in our application is:

    Dim commandString As String = "SELECT " + _"artId, title, topic, " + _"article.authorId as authorId, " + _"name, lines, dateOfPublishing " + _"FROM " + _"article, author " + _"WHERE " + _"author.authorId = article.authorId"

    We have passed a query to select all the articles along with the author's name. Of course youmay want to use a simpler query, such as:

    Dim commandString As String = "SELECT * from article"

    Defining the Data Adapter

    We need to define the Data Adapter (SqlDataAdapter or OleDbDataAdapter). The Data Adapterstores your command (query) and connection. Using the connection and query the DaraAdapterconnects to the database when asked, fetches the result of the query and stores it in a localdataset.

    For SQL Server, a Data Adapter is created like this:

    ' forSql ServerDim dataAdapter As New SqlDataAdapter(commandString, conn)

    And for Access, a data adapter is created like this:

    ' for MS AccessDim dataAdapter As New OleDbDataAdapter(commandString, conn)

    We have created a new instance of the Data Adapter and supplied it the command string andconnection object in the constructor call.

    Creating and filling the DataSetFinally, we need to create an instance of the DataSet. As we mentioned earlier, a DataSet is alocal and offline container of data. The DataSet object is created simply as:

    Dim ds As New DataSet()

    We need to fill the DataSet with the results from the query. We will use the DataAdapter objectfor this purpose and call its Fill() method. This is the step where the Data Adapter connects to

  • 8/8/2019 Introducing ADO

    7/7

    the physical database and fetches the result of the query.

    dataAdapter.Fill(ds, "prog")

    We have called the Fill() method of dataAdapter object. We have supplied it the dataset to filland the name of the table (DataTable) in which the result of query is filled.

    This is all we need to connect and fetch data from the database. Now the results of the query isstored in the dataset object in the prog table, which is an instance of the DataTable. We can get

    a reference to this table by using the indexer property of the DataSet object's Tables collection.

    Dim dataTable As DataTable = ds.Tables("prog")The indexer we have used takes the name of the table in the DataSet and returns the

    corresponding DataTable object. We can use the tables Rows and Columns collections to

    access the data in the table.