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.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
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.
C# programming with database Basic guideline. First step Install SQL Server 2008/2010 (Professional edition if possible) Install Visual Studio 2008/2010.
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.
Developing Web Applications Using Microsoft ® Visual Studio ® 2008.
Accessing SQL Server and OLE DB from.NET Svetlin Nakov Telerik Corporation
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.
CS795/895: Introduction. Topics Distributed Systems –Availability –Performance –Web Services Security –Authentication –Authorization –Confidentiality.
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.
MySQL Connection using ADO.Net Connecting to MySQL from.NET Languages.
1 Introduction to ADO.NET Microsoft ADO.NET 2.0 Step by Step Rebecca M Riordan Microsoft Press, 2006.
11 Using ADO.NET II Textbook Chapter Getting Started Last class we started a simple example of using ADO.NET operations to access the Addresses.
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
Module 9: Accessing Relational Data Using Microsoft Visual Studio.NET.
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
© 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:
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.
C# Programming in Depth Prof. Dr. Bertrand Meyer March 2007 – May 2007 Chair of Software Engineering Lecture 10: Database Lisa (Ling) Liu.
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.
Mauricio Featherman, Ph.D. Washington St. University
Company Confidential 1 Working with Data and ADO.Net.
ADO.NET AND STORED PROCEDURES - Swetha Kulkarni. RDBMS ADO.NET Provider  SqlClient  OracleClient  OleDb  ODBC  SqlServerCE System.Data.SqlClient.
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.
1 11/15/05CS360 Windows Programming ADO.NET Continued.
HNDIT Rapid Application Development
ADO.NET FUNDAMENTALS BEGINNING ASP.NET 3.5 IN C#.
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:
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
 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
SQL commands from C# and ASP.net
ADO.Net and Stored Procedures
Tonga Institute of Higher Education
MySQL Connection using ADO.Net
Database Programming By Abdul Hadi M. Alaidi.
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 CS795

What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net provider---to interface with MS SQL databases without any help from unmanaged providers –OLE DB.Net provider---to interface with other databases through unmanaged OLE DB providers OLE DB providers provide a uniform API over a variety of databases

System.Data.SqlClient using System.Data.SqlClient … SqlConnection conn = new SqlConnection (“server=(local); Initial Catalog = database=pubs; uid=mukka; pwd=“); Or (“server=(local); Initial Catalog = database=pubs; Trusted_Connection=Yes;“); try { conn.Open(); SqlCommand cmd = new SqlCommand(“select * from titles”, conn); SqlDataReader reader = cmd.ExecuteReader (); while (reader.Read ()) Console.Writeln (reader[“title”]); } Catch (SqlException ex) {Console.WriteLine (ex.message); } finally {conn.Close();} Note: For OLEDB, simply replace Sql in the above code by OleDb

Connections, Commands, DataReaders The canonical usage pattern for executing database commands in ADO.Net: 1.Create a connection object encapsulating a connection string 2.Open the connection by calling Open on the connection object 3.Create a command object encapsulating both an SQL command and the connection that the command will use 4.Call a method on the command object to execute the command 5.Close the connection by calling Close on the connection object

SqlConnection Class SqlConnection = conn SqlConnection(); Conn.ConnectionString = “server=localhost; database=pubs; uid=mukka; pwd=“; Or SqlConnection conn = “server=localhost; database=pubs; uid=mukka; pwd=“; Other parameters for ConnectionString: x It can also be defined on web.config: The constructor of the SqlConnection object expects one parameter: the connection string. The connection string identifies the SQL server name, the SQL database name, and satisfies the authorization requirement by providing a user name and a password, or by specifying Trusted_Connection=true. You can specify the connection string in line within the constructor line, or you can specify it in Web.config:

Open and Closing Connections You must first open a connection and close it at the end. SqlConnection conn = new SqlConnection (“server=localhost; database=pubs; uid=mukka; pwd=“); try{ conn.Open(); ….} catch (SqlConnection ex){ …..} finally { conn.Close();}

Command Classes ExecuteReader (for read) ExecuteNonQuery (for updates) SqlConnection conn = new SqlConnection (“server=localhost; datbase=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();}

ExecuteNonQuery To execute operations where database is changed Example: insert, update, delete, create database, create table, etc. Insert, update, delete: Returns number of rows affected by the operation Returns -1 for others SqlCommand cmd = new SqlCommand (“insert into titles (title_id, title, type, pubdate)”+ “values (‘CS150’,’C++ Programming’,” + “ ‘computer science’, ‘May 2006’), conn); cmd.ExecuteNonQuery();

ExecuteScalar Returns the 1 st row of the 1 st column in the result Used for commands such as: count, avg, min, max, sum try{ conn.Open(); SqlCommand cmd = new SqlCommand (“select max (advance) from title”, conn); decimal amount = (decimal) cmd.ExecuteScalar (); Console.WriteLine (“ExecuteScalar returned (0:c)”, amount); } Catch (SqlException ex} {Console.Writeln (ex.Message);} finally {conn.Close();}

ExecuteScalar (cont.) To retrieve BLOBs (Binary large objects) from databases FileStream stream new FileStream (“Logo.jpg”, FileMode.Open); byte[] blob new byte [stream.Length]; stream.Read (blob, 0, (int) stream.Length); stream.Close(); SqlConnection con = new … try{ conn.Open(); SqlCommand cmd = new SqlCommand (“insert into pub_info (pub_id, logo) values conn); cmd.Parameters.Add blob); cmd.ExecuteNonQuery (); } catch … finally …

ExecuteScalar (Cont.) To validate a user name and password (page , Jeff Prosie book) Try { conn.Open(); StringBuilder builder = new StringBuilder (); builder.Append (“select count (*) from users where username = …. int count = (int) command.ExecuteScalar (); return (count > 0); }

ExecuteReader Method To perform database queries Returns a DataReader object: SqlDataReader or OleDataReader 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();

Transactions Ex: transfer funds from one account (say 1234) to another account (say 9876). SqlTransaction trans = null; SqlConnection conn = new SqlConnection (“server=localhost; database=mybank; uid=mukka; pwd=“); try{conn.Open(); trans = conn.BeginTransaction (IsolationLevel.Serializable); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.Transaction=trans; cmd.CommandText = “update accounts set balance = balance-1500 where account_id = ‘1234’ “; cmd.ExecuteNonQuery(); cmd.CommandText = “update accounts set balance = balance+1500 where account_id = ‘9876’ “; cmd.ExecuteNonQuery(); Trans.Commit(); } Alternate to Commit is Rollback.

Parameterized Commands When commands are the same but the parameters are different Try{ conn.Open(); SqlCommand cmd = new SqlCommand(“update accounts set balance = balance”+ where account_id conn); cmd.Parameters.Add SqlDbType.Money); cmd.Parameters.Add SqlDbType.Char); = -1500; = “1234”; cmd.ExecuteNonQuery (); = 1500; = “9867”; cmd.ExecuteNonQuery (); }

Stored Procedures User defined command added to a database Execute faster because they are already in compiled form. CREATE PROCEDURE char char (10); AS BEGIN TRANSACTION UPDATE Accounts SET Balance = Balance WHERE Account_ID IF = 0 BEGIN ROLLBACK TRANSACTION RETURN END UPDATE Accounts SET Balance = Balance WHERE Account_ID IF = 0 BEGIN ROLLBACK TRANSACTION RETURN END COMMIT TRANSACTION GO

How does an application call the stored procedure? SqlConnection conn = new SqlConnection (“server=localhost; database=mybank; uid=mukka; pwd=“); try{conn.Open(); SqlCommand cmd = new SqlCommand (“proc_TransferFunds”, conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add 1500); cmd.Parameters.Add ‘1234’); cmd.Parameters.Add ‘9876’); cmd.ExecuteNonQuery (); } Catch (SqlException ex) { ….} finally {conn.Close(); }

Example where it returns a value CREATE PROCEDURE money OUTPUT AS =Balance From Accounts WHERE Account_ID IF = 1 RETURN 0 ELSE BEGIN = 0 RETURN -1 END GO ***************** SqlConnection conn = new SqlConnection (“server=localhost; database=mybank; uid=mukka; pwd=“); try{conn.Open(); SqlCommand cmd = new SqlCommand (“proc_GetBalance”, conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add ‘1234’); SqlParameter bal = cmd.Parameters.Add SqlDbType.Money); bal.Direction = ParameterDirection.Output; SqlParameter ret = cmd.Parameters.Add SqlDbType.Int); ret.Direction = ParameterDirection.ReturnValue; cmd.ExecuteNonQuery (); int retval = (int) ret.value; decimal balance = (decimal) bal.Value; } catch (SqlException ex) { ….} finally {conn.Close(); }

DataSet Class DatasetDatabase DataTableTable DataRowRecords in a DataTable DataColumnFields in a DataTable DataSet.Tables DataTabe.Rows DataTable.Columns UniuqeConstraintAdd a contsraint to a column DataRelationRelationship between two tables

Dataset (cont.) Datasets are ideal for retrieving results from database queries and storing them in memory. In addition, this data may be modified and propagated back to the database. It can also support, random access to the data (unlike DataReader) Great for caching, especially in web applications.

DataSets vs. DataReaders If the application simply queries a database and reads through the records one at a time until it finds the record it is looking for, DataReader is the right tool If the application requires all results from a query, say to display in a table, and have ability to iterate back and forth through the result set, DataSet is a good alternate.

DataAdapter DataSets don’t interact with databases directly; Instead, they interact through DataAdapters Purpose: To perform database queries and create DataTables containing the query results; also, to write the modified DataTables into databases Fill and Update

DataAdapter.Fill SqlDataAdapter adapter = new SqldataAdapter (“select * from titles”, “server=localhost; database=pubs; uid=mukka; pwd=“); DataSet ds = new dataSet (); adapter.Fill (ds, “Titles”); What does Fill do? (1)Open a connection to the pubs database using adapter. (2)Performs a query on the pubs database using the query string passed to adapter. (3)Creates a DataTable named “Titles” in ds. (4)Initializes DataTable with a schema that matches that of the “Titles” table in the database. (5)Retrieves records produced by the query and writes them to the DataTable (6)Closes the connection to the database

DataTable foreach (DataTable table in ds.Tables) Console.WriteLine (table.TableName); DataTable table = ds.Tables[0]; foreach (DataRow row in table.Rows) Console.WriteLine(row[0]); DataTable table = ds.Tables[0]; foreach (DataRow row in table.Rows) Console.WriteLine(row[“account_id”]); DataTable table = ds.Tables[0]; foreach (DataColumn col in table.Columns) Console.WriteLine(“Name={0}, Type ={1}”, col.ColumnName, col.DataType);

Insert a record into DataTable SqlDataAdapter adapter = new SqldataAdapter (“select * from titles”, “server=localhost; database=pubs; uid=mukka; pwd=“); DataSet ds = new dataSet (); adapter.Fill (ds. “Titles”); DataTable table ds.Tables[“Titles”]; DataRow row = table.NewRow (); row[“title_id”] = “CS795”; row[“title”] = “.Net Security”; row[“price”]=“70.99”; Table.Rows.Add (row);

Propagating Changes back to Database SqlDataAdapter adapter = new SqldataAdapter (“select * from titles”, “server=localhost; database=pubs; uid=mukka; pwd=“); SqlCommandBuilder builder = new SqlCommandBuilder (adapter); DataSet ds = new dataSet (); adapter.Fill (ds. “Titles”); DataTable table ds.Tables[“Titles”]; DataRow row = table.NewRow (); row[“title_id”] = “CS795”; row[“title”] = “.Net Security”; row[“price”]=“70.99”; table.Rows.Add (row); adapter.Update (table); (only writes the ones that were changed)

Links Video 1: Video 2: Video 3: src_vid=Mo0ECWKVVDU&v=pBCPc44CE74Video 3: src_vid=Mo0ECWKVVDU&v=pBCPc44CE74 Video 4: src_vid=pBCPc44CE74&v=vDvV3KrRuMAVideo 4: src_vid=pBCPc44CE74&v=vDvV3KrRuMA Video 5: src_vid=vDvV3KrRuMA&v=Zv9i1S_dkTIVideo 5: src_vid=vDvV3KrRuMA&v=Zv9i1S_dkTI Video 6: rc_vid=Zv9i1S_dkTI&v=QKhHkEmv3KwVideo 6: rc_vid=Zv9i1S_dkTI&v=QKhHkEmv3Kw Video 7: src_vid=QKhHkEmv3Kw&v=stIWeAcO45YVideo 7: src_vid=QKhHkEmv3Kw&v=stIWeAcO45Y Video 8: rc_vid=stIWeAcO45Y&v=EzwBuqILfdsVideo 8: rc_vid=stIWeAcO45Y&v=EzwBuqILfds Video 9: src_vid=EzwBuqILfds&v=rovj0xmM-0MVideo 9: src_vid=EzwBuqILfds&v=rovj0xmM-0M Video 10: &src_vid=rovj0xmM-0M&v=vN-CZYP2ZuYVideo 10: &src_vid=rovj0xmM-0M&v=vN-CZYP2ZuY Video 11: &src_vid=vN-CZYP2ZuY&v=TsKx5CLisSMVideo 11: &src_vid=vN-CZYP2ZuY&v=TsKx5CLisSM

Links The C# Station ADO.NET Tutorial Using ADO.NET for beginners In Depth ASP.NET using ADO.NET