You are on page 1of 20

Modern Programming Language

Lecture-10

Making External Data Available Locally


Agenda
Load

external data into a DataTable or DataSet

Return

updated DataSet content to an external

source
Use

SQL statements and stored procedures to manage DataSet content

Introduction
The

disconnected data experience provided by ADO.NET revolves around the DataSet class and its supporting objects. chapter introduces the DataAdapter class the class that fulfills disconnected core data promise.

This

Understanding Data Adapters


Data

adapters link your external database tables and your local DataSet-managed tables by issuing SQL statements. you need to get data from the database into a DataSet, the adapter must perform a Fill operation, issuing a SELECT statement and moving the results into local DataTable instances. You can then update the values in those DataTable instances. its time to return changes stored in the DataSet to the database, the data adapters Update operation sends the relevant INSERT, UPDATE, and DELETE statements to the database to bring the external data store into line with local changes.

Anytime

When

Diagram of DataAdapter
The

following figure shows the components working on a single database table, Customer.

Cont

The DataAdapter manages a lot of complex activity between the database and a DataSet or DataTable. All the classes introduced so far in our all lessonsfrom DataSet to SqlParameter, from DataRow to DataReadercome into play when creating instances of a data adapter class. The System.Data.SqlClient.SqlDataAdapter class exposes the SQL Server provider implementation of the adapter. You can also find OLE DB and ODBC variations of the data adapter in the classes System.Data.OleDb.OleDbDataAdapter and System.Data.Odbc.OdbcDataAdapter, respectively. All these classes derive from System.Data.Common.DbDataAdapter, which in turn derives from System.Data.Common.DataAdapter.

SqlDataAdapter support features

SqlDataAdapter provides three general support features in your application: Record retrieval: Populating a DataTable with database records represents the minimal functionality of the data adapter. Internally, the SqlDataAdapter uses a DataReader instance to retrieve records out of the database, so you must provide it with a SELECT statement and a connection string. Stored procedures that return data rows also work; the adapter will correctly process multiple record sets returned by the query. Record updating: Moving modifed data back to external storage is a little more in volved. The update operation requires distinct INSERT, UPDATE, and DELETE statements to complete its work. Table and column name mapping: Each data adapter includes a mapping layer that automatically renames tables and columns as needed while data is passed between local and remote storage areas.

Moving Data from Source to Memory


The

SqlDataAdapter.Fill method requests data from SQL Server using a valid SELECT statement or a data-selection stored procedure. After it accesses the data through an internal SqlDataReader, it moves the records into the DataTable or DataSet of your choice. Data into a DataTable:

Moving To

move data from a database table into a DataTable instance, set up a new SqlDataAdapter object and call its Fill method, passing it the instance of the DataTable.
Dim dt As New DataTable() Dim cs As String = "Data source=.;Integrated security=true;Initial catalog=Sale Dim con As New SqlConnection(cs) Dim da As New SqlDataAdapter("Select * from customer", con) da.Fill(dt) DataGridView1.DataSource = dt
As the data adapter reads the incoming data, it examines the schema of that data and builds the columns and properties of the DataTable instance as needed.

Cont

The data adapter uses the constructor arguments to create a new SqlCommand instance. It then assigns this instance to its SelectCommand property, a property that must be set before the SqlDataAdapter can do its data retrieval work.

Pass in a SQL string and SqlConnection pair to the SqlDataAdapter constructor, or just leave off the arguments altogether. The SqlDataAdapter class has no connection string or connection properties, so if you dont provide them with the constructor, you need to include them with a SqlCommand instance that you assign to the SqlDataAdapter.SelectCommand property directly, as shown here:
Dim dt As New DataTable() Dim cs As String = "Data source=.;Integrated security=true;Initial catalog=Sale" Dim con As New SqlConnection(cs) Neither of the preceding examples opened the connection explicitly. If the commands connection isnt open yet, the Fill method opens it for youand closes it when the operation completes.

Dim da As New SqlDataAdapter()


Dim cmd As New SqlCommand("Select * from customer", con) da.SelectCommand = cmd da.Fill(dt) DataGridView1.DataSource = dt

Cont.

The SqlDataAdapter.SelectCommand property is a standard SqlCommand instance, you can use any of that command objects features to access the remote data. This includes adding one or more SqlParameter objects. You can also execute stored procedure.
Dim dt As New DataTable() Dim con As New SqlConnection("Data source=.;Integrated security=true;Initial catalog=Sale") Dim da As New SqlDataAdapter() Dim cmd As New SqlCommand("dbo.GetOrderOfCustomer", con) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@custid", SqlDbType.BigInt) cmd.Parameters("@custid").Value = Me.TextBox1.Text da.SelectCommand = cmd da.Fill(dt) DataGridView1.DataSource = dt

Moving Data into a DataSet


Moving

external data into a waiting DataSet instance is as easy as filling a DataTable. To import the data into a DataSet, call the SqlDataAdapter.Fill method, passing it an instance of DataSet.
Dim ds As New DataSet() Dim cs As String = "Data source=.;Integrated security=true;Initial catalog=Sale" Dim con As New SqlConnection(cs) Dim da As New SqlDataAdapter("Select * from customer", con) da.Fill(ds) DataGridView1.DataSource = ds.Tables(0)

As with a DataTable load, the DataSet version of Fill will autobuild the schema for you. If you want to preconfgure the DataSet schema, you can build its table by hand or call the SqlDataAdapter.FillSchema method just before you call the Fill method. da.FillSchema(ds, SchemaType.Source)

Cont
Fill

names the first created table in the data set Table, as is done when filling a DataTable directly. To alter this default name, specify the new name as a second argument to the Fill method. "Customer")

Da.Fill(targetSet, The

Fill(DataSet) method will import multiple tables if its SelectCommand includes a batch of SELECT statements or a stored procedure that returns multiple result sets. The first table created is still named Table (by default). Subsequent tables are named numerically, with the second table given the name Table1, the third table Table2, and so on.

Moving Data from Memory to Source


After

imported data has been modifed within a DataTable (with or without a surrounding DataSet), the same SqlDataAdapter that brought the data in can move the changes back out to the source. a little more configuring of the data adapter are involved. For the return data trip requires setting up the appropriate data manipulation statements and calling the SqlDataAdapter.Update method.

But

Configuring the Update Commands


The

SqlDataAdapter.SelectCommand property manages the movement of data only from the external source to the local DataSet or DataTable. move data in the other direction or delete data, you need to set up three distinct properties:

To

InsertCommand

UpdateCommand
DeleteCommand

Like SelectCommand, these three properties are SqlCommand instances, each containing a SQL statement (or stored procedure), a SqlConnection reference, and parameters.

The Insert command of DataAdapter


' for Insertion


cmd = New SqlCommand("Insert into customer (custid,custname,Address,Balance) values (@custid,@custname,@Address,@Balance)", con) cmd.Parameters.Add("@custid", SqlDbType.BigInt, 0, "custID") cmd.Parameters.Add("@custname", SqlDbType.VarChar, 30, "custname") cmd.Parameters.Add("@Address", SqlDbType.VarChar, 40, "Address") cmd.Parameters.Add("@Balance", SqlDbType.Decimal, 0.0, "Balance") da.InsertCommand = cmd

da.Update(ds.Tables(0))

The UpdateCommand of DataAdapter


' FOR UPDATION cmd = New SqlCommand("UPDATE Customer SET custname=@custname,Address=@Address, Balance=@Balance WHERE custid=@custid", con) cmd.Parameters.Add("@custname", SqlDbType.VarChar, 20, "custname") cmd.Parameters.Add("@Address", SqlDbType.VarChar, 30, "Address") cmd.Parameters.Add("@Balance", SqlDbType.VarChar, 0.0, "Balance") cmd.Parameters.Add("@Custid", SqlDbType.BigInt, 0, "custid") da.UpdateCommand = cmd da.Update(ds.Tables(0))

The DeleteCommand of DataAdapter

' for Deletion


cmd = New SqlCommand("DELETE FROM Customer WHERE Custid=@Custid", con) cmd.Parameters.Add("@Custid", SqlDbType.BigInt, 0, "CustId") da.DeleteCommand = cmd

Performing the Update

After setting all command properties of Data Adaptoer you simply call the adapters Update method to move those changes into the external database.

You must identify which local source the Update method is to use for the update, which can be either a DataSet (which updates all tables included in that set) or a DataTable.
Da.Update(localTable)

The Update method examines each row in the specifed DataSet or DataTable deciding which rows require an INSERT, UPDATE, or DELETE action; or no action at all.
For each row that needs updating, the adapter raises its own OnRowUpdating event just before issuing the SQL command; then raises the related OnRowUpdated event after the row has been changed in the database.

The SqlCommandBuilder class


It

is a class defined by System.Data.SqlClient namespace and is used to generate commands(insert,delete,update) that can be used to reflect DataSet changes back to a sql server database. method of SqlDataAdapter uses the SqlCommandBuilder's commands to reflect DataSet changes back to a sql server database. SCB New SqlCommandBuilder(da)

Update

Dim

The

SqlCommandBuilder generate the insert, delete and update command for the relevant data adaptor.

Questions???

You might also like