ADO.NET and Stored Procedures

Slides:



Advertisements
Similar presentations
17. Data Access ADO.Net Architecture New Features of ADO.NET
Advertisements

ADO.NET: Working in Disconnected Environment Sergey Baidachni MCT, MCSD, MCDBA.
ADO vs ADO.NET ADOADO.NET Client/server coupledDisconnected collection of data from data server Uses RECORDSET object (contains one table) Uses DATASET.
Chapter 10 ADO. What is ADO? ADO is a Microsoft technology ADO stands for ActiveX Data Objects ADO is a programming interface to access data in a database.
Introduction to Database Processing with ADO.NET.
1 ADO.NET. 2.NET Framework Data Namespaces System.Data –Base set of classes and interfaces for ADO.NET System.Data.Common –Classes shared by the.NET Data.
ADO. NET. What is “ADO.Net”? ADO.Net is a new object model for dealing with databases in.Net. Although some of the concepts are similar to the classical.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
In C# program Before you can start using the ODBC class definitions, you will need to include the right module. using System.Data.Odbc; // ODBC definitions.
ADO.NET – part II August 2004 [ Marmagna Desai]. CONTENTS ADO vs ADO.NET ADO.NET – Managed providers Connecting to Database SqlConnection Selecting Database.
Programming with Visual Basic.NET An Object-Oriented Approach  Chapter 8 Introduction to Database Processing.
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
1 ASP.NET ASP.NET Rina Zviel-Girshin Lecture 4. 2 Overview Data Binding Data Providers Data Connection Data Manipulations.
Developing Web Applications Using Microsoft ® Visual Studio ® 2008.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
PART 1 CREATING THE PRODUCT CATALOG. ROADMAP FOR THIS CHAPTER To implement the departments list, you’ll start with the database and make your way to the.
Databases and Data Access  Introduction to ADO.NET  ADO.NET objects  ADP.NET namespaces  Differences between ADO and ADO.NET.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
.NET Data Access and Manipulation ADO.NET. Overview What is ADO.NET? Disconnected vs. connected data access models ADO.NET Architecture ADO.NET Core Objects.
1 Introduction to ADO.NET Microsoft ADO.NET 2.0 Step by Step Rebecca M Riordan Microsoft Press, 2006.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ADO.Net Basics Ruwan Wijesinghe Trainer.
Objectives In this lesson, you will learn to: *Identify the need for ADO.NET *Identify the features of ADO.NET *Identify the components of the ADO.NET.
ASP.NET Rina Zviel-Girshin Lecture 5
Session 8: ADO.NET. Overview Overview of ADO.NET What is ADO.NET? Using Namespaces The ADO.NET Object Model What is a DataSet? Accessing Data with ADO.NET.
Module 7: Accessing Data by Using ADO.NET
Presented by Joseph J. Sarna Jr. JJS Systems, LLC
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
An Introduction to ADO.Net Marmagna Desai.NET Seminar, Fall-2003.
 It is the primary data access model for.Net applications  Next version of ADO  Can be divided into two parts ◦ Providers ◦ DataSets  Resides in System.Data.
1 Data Classes- DataView DataGridView Control. Objectives 2  Data Class  DataAdapter  DataReader  DataSet  DataTable  DataView  DataGridView Control.
1 11/10/05CS360 Windows Programming ADO.NET. 2 11/10/05CS360 Windows Programming ADO.NET  Behind every great application is a database manager o Amazon.
Why ADO.NET Not your father’s Data Access.
Mauricio Featherman, Ph.D. Washington St. University
1 Avoiding Hacker Attacks. 2 Objectives You will be able to Avoid certain hacker attacks and crashes due to bad inputs from users.
Distributed Database Systems INF413. ADO.NET is a set of classes that comes with the Microsoft.NET framework to facilitate data access from managed languages.
Accessing Data with Microsoft Visual C# Applications.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
HNDIT Rapid Application Development
ADO.NET FUNDAMENTALS BEGINNING ASP.NET 3.5 IN C#.
Module 4 Introduction ADO.NET.
C# .NET Software Development
Active Data Objects Using.Net ADO.Net Farooq Ahmed Amna Umber Summayya Shehzad.
DataGridView. Displaying data in a tabular format is a task you are likely to perform frequently. The DataGridView control is designed to be a complete.
Module 2: Using ADO.NET to Access Data. Overview ADO.NET Architecture Creating an Application That Uses ADO.NET to Access Data Changing Database Records.
Data Access. ADO.NET ADO.NET is the primary library for building database solutions within the.NET Framework. ADO.NET does not replace ADO. ADO and OLEDB.
ADO .NET from. ADO .NET from “ADO .Net” Evolution/History of ADO.NET MICROSOFT .NET “ADO .Net” Evolution/History of ADO.NET History: Most applications.
.NET Data Access and Manipulation
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Using Stored Procedures ADO.NET - Lesson 07  Training time: 15 minutes  Author:
 ADO.NET is an object-oriented set of libraries that allows you to interact with data sources  Commonly, the data source is a database, but it could.
Common SQL keywords. Building and using CASE Tools Data Base with Microsoft SQL-Server and C#
ASP.NET Programming with C# and SQL Server First Edition
Introduction to ADO.NET
Introduction to Database Processing with ADO.NET
Introduction to Database Processing with ADO.NET
ADO.NET Framework.
Distributed Database Systems
Programming the Web Using ASP.Net
How to Create Login Form using vb.net and SqlServer Database
Lecture 6 VB.Net SQL Server.
VB.NET Using Database.
ADO.Net and Stored Procedures
Tonga Institute of Higher Education
מתחברים למסד נתונים היכרות עם ADO.Net.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Browser (Client Side) 瀏覽器 (客戶端)
Chapter 10 ADO.
PROG Advanced Web Apps 4/13/2019 Programming Data Pages Wendi Jollymore, ACES.
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
Introduction to Database Programming through ADO. NET
Presentation transcript:

ADO.NET and Stored Procedures VENKATA CS 795 vpatloll@cs.odu.edu 00787704

Evolution of ADO.NET 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.

What is an ADO.NET 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.

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

Connection object Connects to databases. Provider-specific classes SqlConnection OracleConnection OleDbConnection. Connections can be opened in two ways: Explicitly by calling the “Open” method on the connection Implicitly when using a DataAdapter. Connections handle transactions

Example for connection SqlConnection conn = new SqlConnection (“server=localhost; database=pubs; uid=mukka; pwd=“); try{ conn.Open(); ….} catch (SqlConnection ex){ …..} finally { conn.Close(); }

Command Object Command objects are used to execute commands to a database across a data connection. These provide 3 methods to execute commands on database: ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE or DELETE ExecuteScalar: Returns a single value from a database query ExecuteReader: Returns a result set by way of a DataReader object Provider-specific classes SqlCommand OleDbCommand Results are returned in the form of streams. Accessed by: DataReader object DataSet object via a DataAdapter.

Example for Command Object 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();}

DataReader Object 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.

EXAMPLE for DataReader 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); for (int i=0; I <reader.FieldCount; i++) Console.WriteLine (reader.GetName[i])); } reader.Close();

DataAdapter Object 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.

Example for DataAdapter 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);

DataSet Object 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

Example for DataSet SqlDataAdapter ad = new SqlDataAdapter(“select * from Categories",myConnection); DataSet ds = new DataSet(); ad.Fill(ds,"Categories"); DataGrid1.DataSource = ds; DataGrid1.DataBind();

DataView Object 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

Example for DataAdapter 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' and Country = 'Brazil'", "ContactName", DataViewRowState.CurrentRows); dataGridView1.DataSource = dv;

DataTable Object It holds a table data from a data source; Data tables contains two important properties: COLUMNS 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.

Example for DataTable 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"});

Constraint Object 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.

Example for Adding Constraint to DataTable 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);         }     }

DataRelation Object 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.

Example for DataRelation 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); } ……........ ……......... ……………

ADO.NET using Stored Procedures

Stored Procedure 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. 

Executing a Stored Procedure 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.

Cont… 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.

Sending Parameters to Stored Procedures Using parameters for stored procedures is the same as using parameters for query string commands.  create a command object identifying the stored procedure SqlCommand cmd = new SqlCommand( "CustOrderHist", conn); set the command object so it knows to execute a stored procedure cmd.CommandType = CommandType.StoredProcedure; add parameter to command, which will be passed to the stored procedure cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));

Cont…. 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.

Calling Stored procedures in ADO.NET with an example 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();

Cont… 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

Cont… 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"));

Cont… 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();

Cont… 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();

Refereces 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

Thank you

QUESTIONS ???