36

ADO.NET and Stored Procedures

  • Upload
    kevork

  • View
    27

  • Download
    0

Embed Size (px)

DESCRIPTION

ADO.NET and Stored Procedures. VENKATA CS 795 [email protected] 00787704. Evolution of ADO.NET. The first model used to access database, DAO (data access model) was created for local databases . - PowerPoint PPT Presentation

Citation preview

Page 1: ADO.NET and Stored Procedures
Page 2: ADO.NET and Stored Procedures

The first model used to access database, DAO (data access model) was created for local databases.

Next RDO (Remote Data Object) & ADO (Active Data Object) for Client Server architectures.

ADO was a good architecture but as the language changes so is the technology.

ADO was a connected data access. Which raises concerns about Database Security and network traffic.

Page 3: ADO.NET and Stored Procedures

ADO stands for “ActiveX Data Objects”.

ADO.NET is used to connect application system and database server.

ADO.NET consists of a set of classes used to handle data access and data services.

ADO.NET uses XML to store and transfer data among applications, provide fast access of data for desktop and distributed applications.

ADO.NET is scalable and interoperable.

Page 4: ADO.NET and Stored Procedures

ADO.net Objects are the means to access and modify the data in the Database.

Page 5: ADO.NET and Stored Procedures

Connects to databases.

Provider-specific classes o SqlConnection o OracleConnectiono OleDbConnection.

Connections can be opened in two ways:o Explicitly by calling the “Open” method on the

connectiono Implicitly when using a DataAdapter.

Connections handle transactions

Page 6: ADO.NET and Stored Procedures

SqlConnection conn = new SqlConnection(“server=localhost; database=pubs; uid=mukka;

pwd=“);try{ conn.Open(); ….}catch (SqlConnection ex){ …..}finally { conn.Close();}

Page 7: ADO.NET and Stored Procedures

Command objects are used to execute commands to a database across a data connection.

These provide 3 methods to execute commands on database: o ExecuteNonQuery: Executes commands that have no return

values such as INSERT, UPDATE or DELETE o ExecuteScalar: Returns a single value from a database query o ExecuteReader: Returns a result set by way of a DataReader

object

Provider-specific classeso SqlCommando OleDbCommand

Results are returned in the form of streams. Accessed by:o DataReader objecto DataSet object via a DataAdapter.

Page 8: ADO.NET and Stored Procedures

ExecuteReader (for read)ExecuteNonQuery (for updates)SqlConnection conn = new SqlConnection

(“server=localhost; database=pubs; uid=mukka; pwd=“);try {conn.Open();SqlCommand cmd = new SqlCommand ();cmd.CommandText= “delete from title where title_id =

“xxxx”;cmd.Connection = conn;cmd.ExecuteNonQuery ();}catch (SqlException ex) {….}finally { conn.Close();}

Page 9: ADO.NET and Stored Procedures

Provides methods and properties that deliver a forward-only stream of data rows from a data source.

When a DataReader is used, parts of the ADO.NET model are cut out, providing faster and more efficient data access.

Page 10: ADO.NET and Stored Procedures

try{ conn.Open(); SqlCommand cmd = new SqlCommand(“select *

from titles”, conn);SqlDataReader reader = cmd.ExecuteReader();While (reader.Read()) Console.WriteLine (reader[“title”]); }******************try {conn.Open(); SqlCommand cmd = new

SqlCommand(“select * from titles”, conn);SqlDataReader reader = cmd.ExecuteReader();for (int i=0; I <reader.FieldCount; i++)

Console.WriteLine (reader.GetName[i])); }reader.Close();

Page 11: ADO.NET and Stored Procedures

Provides a set of methods and properties to retrieve and save data between a DataSet and its source data store.

Allows the use of stored procedures.

Connects to the database to fill the DataSet and also update the database.

Types of DataAdapters --SQLDataAdapter.

--ORACLEDataAdapter --OleDbDataAdapter.

Page 12: ADO.NET and Stored Procedures

using System.Data;using System.Data.SqlClient;using System.Windows.Forms;namespace WindowsFormsApplication9{ public partial class Form1 : Form { public Form1()

{ InitializeComponent();

FillData();}void FillData(){ using (SqlConnection c = new SqlConnection(

Properties.Settings.Default.DataConnectionString)) {c.Open();using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM EmployeeIDs",

c)){ DataTable t = new DataTable();a.Fill(t);}}

}}

}

Page 13: ADO.NET and Stored Procedures

Replaces the ADO Recordset.

Represents a cache of data that contains tables, columns, relationships, and constraints, just like a database.

Regardless of where the source data comes from, data can all be placed into DataSet objects.

Tracks changes that are made to the data it holds before updating the source data.

DataSet are also fully XML-featured.

Works with all current models of data storage: flat, relational, and hierarchical

Page 14: ADO.NET and Stored Procedures

SqlDataAdapter ad = new SqlDataAdapter(“select * from Categories",myConnection);

DataSet ds = new DataSet();

ad.Fill(ds,"Categories");

DataGrid1.DataSource = ds;

DataGrid1.DataBind();

Page 15: ADO.NET and Stored Procedures

Provides methods and properties that enable UI objects such as a DataGrid to bind to a DataSet.

A view of the data contained in the DataSet.

Only used in conjunction with a DataSet

Page 16: ADO.NET and Stored Procedures

string connectionString = "..Nortwind Connection String.."; DataTable customers = new DataTable("Customers");

using (SqlConnection connection =new SqlConnection(connectionString)) {

SqlCommand selectAllCustomers = connection.CreateCommand(); selectAllCustomers.CommandText = "SELECT * FROM [Customers]"; connection.Open(); customers.Load(selectAllCustomers.ExecuteReader(CommandBehavior.CloseConnection)); } DataView dv = new DataView(customers,"Region = 'SP' andCountry = 'Brazil'", "ContactName",DataViewRowState.CurrentRows); dataGridView1.DataSource = dv;

Page 17: ADO.NET and Stored Procedures

It holds a table data from a data source; Data tables contains two important properties:

1. COLUMNS2. ROWS

-- DataRow Objects: Datarow objects correspond to a particular row in a table. We use “Item” property to get or set a value in a particular field in row.

-- DataColumn Objects: DataColumn objects represent the columns in the table. Each DataColumn has a data type which specify which type of data column contains.

Page 18: ADO.NET and Stored Procedures

DataSet dset; DataTable dtbl;DataRow drow; drow=dtbl.NewRow(); drow["LastName"]="Altindag"; drow[1]="Altindag"; dtbl.Rows.Add(drow); dtbl.Rows.Add(new object[] {1, "Altindag"});

Page 19: ADO.NET and Stored Procedures

Dataset support constraint objects to check data integrity

Constraints are of two types: Unique Constraint and foreign constraint.

-- Unique Constraint check that new record entered is unique throughout table

-- Foreign constraint specify that if one table is updated, how the related records in another table would be affected.

--Not NULL constraint: it is used to check whether the column with this constraint is filled or not.

Page 20: ADO.NET and Stored Procedures

using System;using System.Data;

    class Program    {        static void Main(string[] args)        {            DataTable dt1 = new DataTable("Table-1");            DataColumn pkCol = dt1.Columns.Add("Id", typeof(int));            dt1.Columns.Add("Field1", typeof(string)).MaxLength = 50;            dt1.PrimaryKey = new DataColumn[] { pkCol };

            DataTable dt2 = new DataTable("Table-2");            dt2.Columns.Add("Id", typeof(int));            dt2.Columns.Add("Field1", typeof(string)).MaxLength = 50;            UniqueConstraint uc = new UniqueConstraint("PrimaryKey-2", dt2.Columns["Id"], true);            dt2.Constraints.Add(uc);

            DataTable dt3 = new DataTable("Table-3");            dt3.Columns.Add("Id1", typeof(int));            dt3.Columns.Add("Id2", typeof(int));            dt3.Columns.Add("Field1", typeof(string)).MaxLength = 50;            dt3.Constraints.Add("PrimaryKey-3",new DataColumn[] { dt3.Columns["Id1"], dt3.Columns["Id2"] },true);

        }    }

Page 21: ADO.NET and Stored Procedures

Data Relation objects specify a relationship between parent and child tables, based on a key that both tables share.

You can then use the DataRelation object to get related records.

Page 22: ADO.NET and Stored Procedures

private void Page_Load(object sender, System.EventArgs e){           

 DataSet ds = GetDataSet(); ds.EnforceConstraints = false; DataRelation dl = new DataRelation("CHILDREN",ds.Tables[0].Columns["id"], ds.Tables[1].Columns["parent"], false); dl.Nested = true; ds.Relations.Add(dl);

 ComputeHierarchy(ds.Tables[0].Select("[parent] is null"), 0); }

……........…….........……………

Page 23: ADO.NET and Stored Procedures
Page 24: ADO.NET and Stored Procedures

A stored procedure is a pre-defined, reusable routine that is stored in a database. 

SQL Server compiles stored procedures, which makes them more efficient to use. 

Therefore, rather than dynamically building queries in the code, we can take advantage of the reuse and performance benefits of stored procedures. 

Page 25: ADO.NET and Stored Procedures

In addition to commands built with strings, the SqlCommand type can be used to execute stored procedures. 

There are two tasks require to make this happen: 1. let the SqlCommand object know which stored

procedure to execute. // create a command object identifying the stored

procedure SqlCommand cmd = new SqlCommand( “xxxxx”, conn); While declaring the SqlCommand object above, the first

parameter “xxxxx” is the name of a stored procedure in the database.  The second parameter is the connection object, which is used for executing query strings.

Page 26: ADO.NET and Stored Procedures

2. tell the SqlCommand object that it is executing a stored procedure.set the command object so that it knows to execute a stored procedure

cmd.CommandType = CommandType.StoredProcedure;

The second command tells the SqlCommand object what type of command it will execute by setting its Command Type property to the Stored Procedure.

Page 27: ADO.NET and Stored Procedures

Using parameters for stored procedures is the same as using parameters for query string commands. 

1. create a command object identifying the stored procedure SqlCommand cmd = new SqlCommand( "CustOrderHist", conn);

2. set the command object so it knows to execute a stored procedure cmd.CommandType = CommandType.StoredProcedure;

3. add parameter to command, which will be passed to the stored procedure

cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));

Page 28: ADO.NET and Stored Procedures

The SqlCommand constructor above specifies the name of a stored procedure. 

This particular stored procedure takes a single parameter, named “@CustomerID”.  Therefore, we must populate this parameter using a SqlParameter object. 

The name of the parameter passed as the first parameter to the SqlParameter constructor must be spelled exactly the same as the stored procedure parameter.  Then execute the command the same as you would with any other SqlCommand object.

Page 29: ADO.NET and Stored Procedures

Initially create a object of SqlConnection class which is available in System.Data.SqlClient namespace.

We have to provide the connection string as a parameter which includes the Data Source name, the database name and the authentication credentials.

Open the connection using the Open() method.

SqlConnection con = new SqlConnection("Data Source= ; initial catalog= Northwind ; User Id= ; Password= '");

con.open();

Page 30: ADO.NET and Stored Procedures

Create the following stored procedure on the Region table in the Northwind database which accepts two parameters and does not have any output parameters.

CREATE PROCEDURE RegionUpdate (@RegionID INTEGER, @RegionDescription NCHAR(50)) AS

SET NOCOUNT OFF UPDATE Region SET RegionDescription = @RegionDescription

Page 31: ADO.NET and Stored Procedures

Create a SqlCommand object with the parameters as the name of the stored procedure that is to be executed and the connection object “con” to which the command is to be sent for execution.

SqlCommand command = new SqlCommand("RegionUpdate",con);

Change the command objects CommandType property to stored procedure.

command.CommandType = CommandType.StoredProcedure;

Add the parameters to the command object using the Parameters collection and the SqlParameter class.

command.Parameters.Add(new SqlParameter ("@RegionID",SqlDbType.Int,0,"RegionID"));

Page 32: ADO.NET and Stored Procedures

command.Parameters.Add(new SqlParameter ("@RegionDescription",SqlDbType.NChar,50,"RegionDescription"));

Specify the values of the parameters using the Value property of the parameters.

command.Parameters[0].Value=4;command.Parameters[1].Value="SouthEast";

Excecute the stored procedure using the ExecuteNonQuery method which returns the number of rows effected by the stored procedure.

int i=command.ExecuteNonQuery();

Page 33: ADO.NET and Stored Procedures

Call the stored procedure and access the RegionDescription for the RegionID 4 using the value property of the parameter.

string newRegionDescription =(string) command.Parameters["@RegionDescription"].Value;

Close the sql connection.

con.Close();

Page 34: ADO.NET and Stored Procedures

http://www.startvbdotnet.com/ado/default.aspx

http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx.

http://www.codeproject.com/KB/cs/simplecodeasp.aspx.

http://www.developer.com/db/article.php/3438221/Calling-Stored-Procedures-with-ADONET.htm

Page 35: ADO.NET and Stored Procedures
Page 36: ADO.NET and Stored Procedures