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.
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.
Chapter 12 ADO.NET Yingcai Xiao. Introduction to Database.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 12 Database Connectivity with ASP.NET JavaScript, Third Edition.
Objective In this session we will discuss about : What is ADO. 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.
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.
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.
Neal Stublen Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating.
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
Neal Stublen Tonight’s Agenda  Database Errors  Parameterized queries  ToolStrip control  Master-detail relationships  Custom.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Introduction to ADO.NET ADO.NET - Lesson 01  Training time: 10 minutes  Author:
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.
Module 3: Performing Connected Database Operations.
 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 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.
Company Confidential 1 Working with Data and ADO.Net.
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.
1 11/15/05CS360 Windows Programming ADO.NET Continued.
HNDIT Rapid Application Development
Module 4 Introduction ADO.NET.
1 Database Programming with ADO.NET Kashef Mughal.
C# .NET Software Development
Active Data Objects Using.Net ADO.Net Farooq Ahmed Amna Umber Summayya Shehzad.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 The SqlCommand Object ADO.NET - Lesson 03  Training time: 15 minutes  Author:
Introduction to Database C# MySQL onnect-C-to-MySQL 1.
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
C# MySQL onnect-C-to-MySQL 1.
 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.
ASP.NET Programming with C# and SQL Server First Edition
Data Access with ADO.NET
Introduction to ADO.NET
Introduction to Database Processing with ADO.NET
Introduction to Database Processing with ADO.NET
ADO.NET and Stored Procedures
ADO.NET Framework.
Programming the Web Using ASP.Net
How to Create Login Form using vb.net and SqlServer Database
Lecture 6 VB.Net SQL Server.
Active Data Objects Binding ASP.NET Controls to Data
Introduction to Database
VB.NET Using Database.
Tonga Institute of Higher Education
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
MySQL Connection using ADO.Net
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 By Radhika Malladi

Introduction ADO.Net : database API, used for managed applications It consists of a set of classes Integrates with XML It provides components for creating distributed, data-sharing applications It is used to connect to data source for retrieving, updating and manipulating data.

Introduction cont. Data providers are used to connect to the database, to execute commands and retrieving results ADO.Net provides two data providers SQL Server .Net provider – Interfaces MicrosoftSQLServer with Managed applications(System.data.SqlClient) OLE DB .Net provider – Interfaces databases with UnManaged OLE DB providers(System.data.OleDb)

Design Goals ADO.Net is designed to meet the following goals: Leverage current ADO knowledge Support N-tier programming model ("Any number of levels arranged above another, each serving distinct and separate tasks.“) Done by using Data Set because Data Set works well with all providers Integrating XML

ADO.Net Components Two main components: Data Set – disconnected architecture of ADO.Net .Net data provider components – for data manipulation and read-only access to data Connection – to make connections to database Command – access to database commands Data Reader – provides stream of data from data source Data Adapter – bridge between Data Set object and data source

Architecture

.Net provider Components Connection : SqlConnection conn = new SqlConnection     ("server=localhost;database=a1;uid=sa;pwd="); SqlConnection conn = new SqlConnection     ("server=xyz\malladi;database=a1;uid=sa;pwd="); SqlConnection conn = new SqlConnection     ("server=xyz\malladi;database=a1;uid=sa;pwd=;min pool size=10;max pool size=50;connect timeout=10;Integrated Security = false;Pooling = true;"); OleDbConnection conn = new OleDbConnection      ("provider=sqloledb;data source=localhost;OLE DB Services=-2" +     "initial catalog=a1;user id=sa;password=");

.Net Components cont. Command: SqlCommand cmd = new SqlCommand ("select * from users", conn); Properties: CommadTimeout , CommandText Methods: ExecuteNonQuery() – This returns number of rows affected Ex: Insert, Delete, Update (no return values) ExecuteScalar() – single row, single column values Ex: count, min, max, sum, avg etc and to retrive BLOBs ExecuteReader()

.Net Components cont. Data Reader: SqlDataReader reader = cmd.ExecuteReader (); ExecuteReader() – obtains query results quickly for read-only. Ex: Select reader.close(); Methods: GetName – retrieve field names GetValue – retrieve field values(returns obj) GetOrdinal – converts field name into numeric index

.Net Components cont. Data Adapter: SqlDataAdapter adapter = new SqlDataAdapter ("select * from users",     "server=localhost;database=a1;uid=sa;pwd=");

Example (ExecuteReader) SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Inetpub\\wwwroot\\Assign2\\App_Data\\a2.mdf;Integrated Security=True;User Instance=True"); try { con.Open(); SqlCommand cmd = new SqlCommand("select role from users where username = '" + TextBox1.Text.Trim() + "' and password = '" + TextBox2.Text.Trim() + "'", con); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) role = dr.GetString(dr.GetOrdinal("role")); break; } catch (SqlException ex) Response.Write(ex.Message); finally con.Close();

Example (ExecuteScalar) SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\inetpub\\wwwroot\\Assign2\\App_Data\\a2.mdf;Integrated Security=True;User Instance=True"); try{ connection.Open(); StringBuilder builder = new StringBuilder(); builder.Append("select count (*) from users where username = \'"); builder.Append(username); builder.Append("\' and cast (rtrim (password) as varbinary) = cast (\'"); builder.Append(password); builder.Append("\' as varbinary)"); SqlCommand command = new SqlCommand(builder.ToString(),connection); int count = (int)command.ExecuteScalar(); return (count > 0); } catch (SqlException) { return false; } finally { connection.Close(); }

Example (ExecuteNonQuery) SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Inetpub\\wwwroot\\Assign2\\App_Data\\a2.mdf;Integrated Security=True;User Instance=True"); try { con.Open(); SqlCommand cmd = new SqlCommand("insert into users (username,password,role)values('" + TextBox6.Text.Trim() + "','" + TextBox7.Text.Trim() + "','" + DropDownList1.SelectedValue + "')", con); int noofrows = cmd.ExecuteNonQuery(); if (noofrows != 0) Response.Write("user created successfully"); } catch (SqlException ex) { Response.Write(ex.Message); } finally { con.Close(); }

Data Set and Data Adapters Set based access – captures query into memory and supports traversal through result set This has 2 classes Data Set : in-memory database Data Adapter : bridge between Data Set and data source Perform database queries create DataTables containing query results Capable of writing changes made to data tables back to database

Data Adapter Two versions: SqlDataAdapter and OleDbDataAdapter Main Methods of Data Adapter are Fill and Update Namespace – system.data.common.DbDataAdapter

Data Adapter cont. Fill: SqlDataAdapter adapter = new SqlDataAdapter ("select * from users",     "server=localhost;database=a1;uid=sa;pwd="); DataSet ds = new DataSet (); adapter.Fill (ds, “users"); Update : adapter.Update (table); Builder for Insert, Update, Delete: SqlCommandBuilder builder = new SqlCommandBuilder (adapter);

Data Set DataSet object – supports disconnected, distributed data with ADO.Net Can be used with multiple and differing data sources It represents complete set of data like related tables, constraints and relationships among tables

Data Set cont.

Data Set cont. DataTable Collection : contains collection of tables DataRelationCollection: contains relationships of tables ExtendingProperties: Property Collection where customized information can be placed Ex: Date/Time when data is generated

Example to insert records SqlDataAdapter adapter = new SqlDataAdapter ("select * from titles", "server=localhost;database=pubs;uid=sa;pwd="); DataSet ds = new DataSet (); adapter.Fill (ds, "Titles"); // Create a new DataRow DataTable table = ds.Tables["Titles"]; DataRow row = table.NewRow (); // Initialize the DataRow row["title_id"] = "JP1001"; row["title"] = "Programming Microsoft .NET"; row["price"] = "59.99"; row["ytd_sales"] = "1000000"; row["type"] = "business"; row["pubdate"] = "May 2002"; // Add the DataRow to the DataTable table.Rows.Add (row);

Examples to select records DataRow[] rows = table.Select ("title_id = 'JP1001'"); DataRow[] rows = table.Select ("price < 10.00"); DataRow[] rows = table.Select ("pubdate >= '#1/1/2000#'"); DataRow[] rows = table.Select ("state in ('ca', 'tn', 'wa')"); DataRow[] rows = table.Select ("state like 'ca*'"); DataRow[] rows = table.Select ("isnull (state, 0) = 0"); DataRow[] rows = table.Select ("state = 'tn' and zip like '37*'");

Example to update records SqlDataAdapter adapter = new SqlDataAdapter ("select * from titles", "server=localhost;database=pubs;uid=sa;pwd="); DataSet ds = new DataSet (); adapter.Fill (ds, "Titles"); DataRow[] rows = table.Select ("ytd_sales > 10000"); foreach (DataRow row in rows) row["price"] = (decimal) row["price"] + 10.00m;

Example to delete records SqlDataAdapter adapter = new SqlDataAdapter ("select * from titles", "server=localhost;database=pubs;uid=sa;pwd="); DataSet ds = new DataSet (); adapter.Fill (ds, "Titles"); DataRow[] rows = table.Select ("ytd_sales < 10000 OR isnull (ytd_sales, 0) = 0"); foreach (DataRow row in rows) row.Delete ();

Example for Updating the database SqlDataAdapter adapter = new SqlDataAdapter ("select * from titles", "server=localhost;database=pubs;uid=sa;pwd="); SqlCommandBuilder builder = new SqlCommandBuilder (adapter); DataSet ds = new DataSet (); adapter.Fill (ds, "Titles"); // Insert a record DataTable table = ds.Tables["Titles"]; DataRow row = table.NewRow (); row["title_id"] = "JP1001"; row["title"] = "Programming Microsoft .NET"; row["price"] = 59.99m; row["ytd_sales"] = 1000000; row["type"] = "business"; row["pubdate"] = new DateTime (2002, 5, 1); table.Rows.Add (row); // Update the database adapter.Update (table);

Stored Procedures User defined command added to a database Executes faster as they are already complied Improves performance ADO.Net supports stored procedures An Example of stored procedure is..

CREATE PROCEDURE proc_TransferFunds @Amount money, @From char (10), @To char (10) AS BEGIN TRANSACTION UPDATE Accounts SET Balance = Balance @Amount WHERE Account_ID = @From IF @@ROWCOUNT = 0 BEGIN ROLLBACK TRANSACTION RETURN END UPDATE Accounts SET Balance = Balance + @Amount WHERE Account_ID = @To IF @@ROWCOUNT = 0 BEGIN RETURN END COMMIT TRANSACTION GO

catch (SqlException ex) { // TODO: Handle the exception } SqlConnection conn = new SqlConnection     ("server=localhost;database=mybank;uid=sa;pwd="); try {      conn.Open ();      SqlCommand cmd = new SqlCommand ("proc_TransferFunds", conn);     cmd.CommandType = CommandType.StoredProcedure;      cmd.Parameters.Add ("@amount", 1000);     cmd.Parameters.Add ("@from", 1111);      cmd.Parameters.Add ("@to", 2222);     cmd.ExecuteNonQuery (); } catch (SqlException ex) {     // TODO: Handle the exception } finally {     conn.Close (); }

Transacted Commands Example SqlConnection conn = new SqlConnection ("server=localhost;database=mybank;uid=sa;pwd="); try { conn.Open (); // Debit $1,000 from account 1111 SqlCommand cmd = new SqlCommand ("update accounts set balance = balance -1000 where account_id = '1111'", conn); cmd.ExecuteNonQuery (); // Credit $1,000 to account 2222 cmd.CommandText = "update accounts set balance = " + "balance + 1000 where account_id = '2222'"; cmd.ExecuteNonQuery (); } catch (SqlException ex) { // TODO: Handle the exception } finally { conn.Close (); }

Transacted Commands Example SqlTransaction trans = null; SqlConnection conn = new SqlConnection     ("server=localhost;database=mybank;uid=sa;pwd="); try {     conn.Open ();     // Start a local transaction     trans = conn.BeginTransaction (IsolationLevel.Serializable);      // Create and initialize a SqlCommand object     SqlCommand cmd = new SqlCommand ();     cmd.Connection = conn;     cmd.Transaction = trans;      // Debit $1,000 from account 1111      cmd.CommandText = "update accounts set balance = balance - 1000 where account_id = '1111'";      cmd.ExecuteNonQuery ();     // Credit $1,000 to account 2222      cmd.CommandText = "update accounts set balance = " +         "balance + 1000 where account_id = '2222'";      cmd.ExecuteNonQuery ();      // Commit the transaction (commit changes)      trans.Commit (); } catch (SqlException) {     // Abort the transaction (roll back changes)  if (trans != null) trans.Rollback (); } finally {     conn.Close (); }

Parameterized Commands Example SqlConnection conn = new SqlConnection ("server=localhost;database=mybank;uid=sa;pwd="); try { conn.Open (); // Create and initialize a SqlCommand object SqlCommand cmd = new SqlCommand("update accounts set balance = balance + @amount " + "where account_id = @id", conn); cmd.Parameters.Add ("@amount", SqlDbType.Money); cmd.Parameters.Add ("@id", SqlDbType.Char); // Debit $1,000 from account 1111 cmd.Parameters["@amount"].Value = -1000; cmd.Parameters["@id"].Value = "1111"; cmd.ExecuteNonQuery (); // Credit $1,000 to account 2222 cmd.Parameters["@amount"].Value = 1000; cmd.Parameters["@id"].Value = "2222"; cmd.ExecuteNonQuery (); } catch (SqlException ex) { // TODO: Handle the exception } finally { conn.Close (); }

Programming Microsoft .Net by Jeff Prosise References ADO.Net by Alex Homer Programming Microsoft .Net by Jeff Prosise http://msdn2.microsoft.com/en-us/library/e80y5yhx(VS.71).aspx http://www.ondotnet.com/pub/a/dotnet/excerpt/progvisbasic_ch08/index.html

Thank you