You are on page 1of 25

ADO.

NET
By Sunil Mallya
Microsoft Student Champ
VI SEM,CS
PESIT

Mail:
sunil.mallya@yahoo.com
Agenda
 Why a new data access technology ?
 ADO.NET Overview.
 ADO.NET object model
 .NET data providers
 Datasets
Why not ADO ???
 ADO was not built to work with
XML data, though some versions
of ADO have added XML
features.
 Contents of multiple Recordset
objects cannot be combined.
 Does not provide support to
submit changes via stored
procedures.
ADO.NET

 ADO.NET is a set of libraries to


help communicate with various
data sources.

 Provides a unified programming


model to deal with disparate
data sources.
What ADO.NET brings ???
 Disconnected data architecture
 Tight integration with XML
 Common data representation
with the ability to combine data
from multiple and varied data
sources
 Optimized facilities for
interacting with a database, all
native to the .NET Framework.
Data Access Architecture
.NET Data Providers
CONNECTION : Establishes a
connection to a specific data
source
COMMAND : Executes a command
against a data source. Exposes
Parameters and can execute within
the scope of a Transaction from a
Connection.
.NET Data Providers
contd..
DataReader : Reads a forward-only,
read-only stream of data from a data
source.
DataAdapter : Populates a DataSet and
resolves updates with the data
source.
What are we creating
Today??
 Simple Application which Will

 Read From Database


 Change Its contents
 Delete Rows.
 Update
Connect to a Acess DB
 First Create a Access Database Phone.mdb
 Create Table “PhoneNumbers”.
 Create two Text Fields : Phonenum ,
Subscriber

 Now Connect this to Our Windows


application …
 public static string connectionString =
"provider=Microsoft.JET.OLEDB.4.0; "
+ "data source = " +
Application.StartupPath + "\\Phone.mdb";
In Form_Load
 // Default select command on the PhoneNumbers table
 string commandstring = "select * from
PhoneNumbers";

 // The link between the sql command and the


database connection
 dataAdapter = new
OleDbDataAdapter(commandstring, connectionString);

 // Define insert, update, and delete sql commands to


use.
 BuildCommands();

 // Declare and fill the in-memory dataset from the


database
 dataSet = new DataSet();
 dataSet.CaseSensitive = true;
 dataAdapter.Fill(dataSet, "PhoneNumbers");
Show all rows in the
listbox
 Fill_lb() {

 dataTable = dataSet.Tables[0];
 listBox1.Items.Clear();

 foreach (DataRow dataRow in


dataTable.Rows)
 {
 LoadBuffers(dataRow);
 listBox1.Items.Add(Phonenum + "\t\t" +
Subscriber);
 }
 }
LoadBuffers
 private void LoadBuffers(DataRow prow)
 {
 Phonenum =
prow["Phonenum"].ToString().Trim(); //
Trims Space
 Subscriber =
prow["Subscriber"].ToString().Trim();

 }
Show in List Box
 private void FillForm()
 {
 txtPhonenum.Text = Phonenum;
 txtSubscriber.Text = Subscriber;
 }
 private void listBox1_SelectedIndexChanged
 {

 DataRow sourceRow =
dataTable.Rows[listBox1.SelectedIndex];
 LoadBuffers(sourceRow);
 FillForm();
BuildCommands()
// Use the select command's connection again
OleDbConnection connection =

(OleDbConnection)dataAdapter.SelectCommand.Connection;

// Declare a reusable insert command with


parameters
dataAdapter.InsertCommand =
connection.CreateCommand();

dataAdapter.InsertCommand.CommandText =
"insert into PhoneNumbers " +
"(Phonenum, Subscriber) " +
"values " +
"(?, ?)";

dataAdapter.InsertCommand.Parameters.Add("Phonenum",
OleDbType.Char, 0, "Phonenum");
Declare a reusable update
command with parameters
 dataAdapter.UpdateCommand =
connection.CreateCommand();

dataAdapter.UpdateCommand.CommandText =
"update PhoneNumbers " +
 "set Subscriber = ? " +
 "where Phonenum = ? ";

dataAdapter.UpdateCommand.Parameters.Add("S
ubscriber", OleDbType.Char, 0, "Subscriber");

dataAdapter.UpdateCommand.Parameters.Add("P
honenum", OleDbType.Char, 0, "Phonenum");
Declare a reusable delete
command with parameters
 dataAdapter.DeleteCommand =
connection.CreateCommand();

dataAdapter.DeleteCommand.Comm
andText =
 "delete from
PhoneNumbers where Phonenum = ?
";

dataAdapter.DeleteCommand.Parame
ADD ENTRY INTO DATABASE

 // create a new row, populate it


 DataRow newRow = dataTable.NewRow();

 newRow["Phonenum"] = txtPhonenum.Text.Trim();
 newRow["Subscriber"] = txtSubscriber.Text.Trim();
 // update the database
 try
 {

dataSet.Tables["PhoneNumbers"].Rows.Add(newRow);
 dataAdapter.Update(dataSet, "PhoneNumbers");
 dataSet.AcceptChanges();
 // inform the user
 MessageBox.Show("Updated.");
 Application.DoEvents();
 // refresh the listbox
 Fill_lb();
 }
Add cont…
 catch (OleDbException ex)
 {
 dataSet.RejectChanges();

MessageBox.Show(ex.Message);

MessageBox.Show(ex.ErrorCode.ToSt
ring());
 }
DELETE RECORDS
 // fetch the selected row in the listbox
 DataRow selectedRow =
dataTable.Rows[listBox1.SelectedIndex];

 string msg = selectedRow["Phonenum"] +


" deleted.";

// delete the selected row


 selectedRow.Delete();
 try
 {
 dataAdapter.Update(dataSet,
"PhoneNumbers");
 dataSet.AcceptChanges();
 // refresh the listbox after the delete
 Fill_lb();

 // inform the user


 MessageBox.Show(msg);
 Application.DoEvents();
 }
 catch (OleDbException ex)
 {
 dataSet.RejectChanges();
 MessageBox.Show(ex.Message);
MODIFY RECORDS IN DB
 // get the selected row
 DataRow selectedRow = dataTable.Rows[listBox1.SelectedIndex];

 // inform the user

 Application.DoEvents();

 // Begin an edit transaction on the row.


 selectedRow.BeginEdit();
 selectedRow["Subscriber"] = txtSubscriber.Text.Trim();
 selectedRow.EndEdit();

 // retrieve each row that changed


 DataSet dsChanges =
 dataSet.GetChanges(DataRowState.Modified);

 // check for any changed rows with errors


 bool okayFlag = true;
 if (dsChanges.HasErrors)
 {
 okayFlag = false;
 string msg = "Error in row";


 // Look at each table in the dataSet
 foreach (DataTable currTable in dsChanges.Tables)
 {
 // Find the rows with errors if any table has errors
 if (currTable.HasErrors)
 {
 // fetch the error rows
 DataRow[] errorRows = currTable.GetErrors();

 // Go through the rows and identify the ones


 // with errors
 foreach (DataRow currRow in errorRows)
 {
 msg = msg + currRow["Phonenum"];
 }
 }
 }
 MessageBox.Show(msg);
 }


 // No errors -- all okay
 if (okayFlag)
 {
 // apply updates to the database
 dataAdapter.Update(dsChanges, "PhoneNumbers");

 // tell the user


 MessageBox.Show("Updated " +
selectedRow["Phonenum"]);
 Application.DoEvents();

 // apply changes and refresh the listbox


 dataSet.AcceptChanges();
 Fill_lb();
 }
 else // if any errors then throw out the changes
 dataSet.RejectChanges();
JOIN :: http://groups.msn.com/bdotnetstudent

Sunil Mallya
Mail to :
sunil.mallya@yahoo.com

You might also like