Vous êtes sur la page 1sur 42

C# - ADO.

NET

www.1000projects.com www.fullinterview.com www.chetanasprojects.com

Course Topics
1. Data Providers 2. ADO.NET Objects 3. ADO.NET Architecture 4. Connection Object 5. Command Object 6. DataReader Object 7. Working with Disconnected Data 8. DataAdapter Object 9. Dataset Object 10. Adding Parameters to Command 11. Working with Stored Procedures

Why ADO.NET?
 ADO.NET - the data-access component of the Microsoft .NET Framework - works with any component on any platform that understands XML.  Interoperability: ADO.NET applications can take advantage of the flexibility and broad acceptance of XML. Because XML is the format for transmitting datasets across the network, any component that can read the XML format can process data.  Programmability: ADO.NET data components in Visual Studio encapsulate data access functionality in various ways that help you program more quickly and with fewer mistakes.  Performance: For disconnected applications, ADO.NET datasets offer performance advantages over ADO disconnected Recordsets.
3

Data Providers
 ADO.NET allows us to interact with different types of data sources.  ADO.NET provides a relatively common way to interact with data sources, but comes in different sets of libraries for each data source.  ADO.NET Data Providers are class libraries that allow a common way to interact with specific data sources or protocols.

Data Providers
.NET Framework Data Provides data access for Microsoft SQL Provider for SQL Server Server version 7.0 or later. Uses the System.Data.SqlClient namespace. .NET Framework Data Provider for OLE DB .NET Framework Data Provider for ODBC .NET Framework Data Provider for Oracle For data sources exposed using OLE DB. Uses the System.Data.OleDb namespace. For data sources exposed using ODBC. Uses the System.Data.Odbc namespace. For Oracle data sources. The .NET Framework Data Provider for Oracle supports Oracle client software version 8.1.7 and later, and uses the System.Data.OracleClient namespace.
5

ADO.NET Architecture

*Source from msdn

ADO.NET Architecture (Connected)


.Net Framework Data Provider

Connection

Database

Command

Application

DataReader

ADO.NET Architecture (Disconnected)

Connection

DataAdapter
Database

Application DataSet

DataView

ADO.NET Objects
 ADO.NET includes many objects you can use to work with data.

The following Object are the Core Object for ADO.NET.


 Connection Object  Command Object  DataReader Object  DataAdapter Object  DataSet Object

The Connection Object


 

   

To interact with a data base, you must have a connection to it. The connection helps to specify the data base server, the data base name, user name, password and other parameters that are required for connecting to the data base. A connection object is used by command objects so they will know which data base to execute the command on. The first thing you will need to do when interacting with a data base is to create a connection. The connection tells the rest of the ADO.NET code which data base it is talking to. This makes it easy for you because the most work you will have to do in code is instantiate the connection object, open the connection and then close the connection when you are done.
10

Creating SqlConnection Object


 

A SqlConnection is an object, just like any other C# object. Most of the time, you just declare and instantiate the SqlConnection all at the same time.

11

SqlConnection Object
Parameter Name Data Source Initial Catalog Integrated Security User ID Password Description Identifies the server. Could be local machine, machine domain name, or IP Address. Data base name. Set to SSPI (Security Support Provider Interface ) to make connection with user's Windows login Name of user configured in SQL Server. Password matching SQL Server User ID.
12

Using SqlConnection


SqlCommand and a SqlDataAdapter Objects take a Connection object as a parameter. The sequences of operations occurring in the lifetime of a SqlConnection are as follows:  Instantiate the SqlConnection.  Open the Connection.  Pass the Connection to other ADO.NET objects.  Perform data base operations with the other ADO.NET objects.  Close the Connection.

13

The SQLCommand Object




   

The process of interacting with a data base means that you must specify the actions you want to occur. This is done with a Command object. You use a Command object to send SQL statements to the data base. A Command object uses a Connection object to figure out which data base to communicate with. A Command object allows you to specify what type of interaction you want to perform with a data base. You can use a Command object alone, to execute a command directly, or assign a reference to a Command object to an SqlDataAdapter, which holds a set of commands that work on a group of data.
14

Creating SQLCommand Object


 

Similar to other C# objects, you instantiate a SqlCommand object via the new instance declaration. It takes a string parameter that holds the command you want to execute and a reference to a SqlConnection object.

15

Command Types


Each strongly typed Command object also supports a CommandType enumeration that specifies how a command string is interpreted. Command Type Description An SQL command defining the statements to be executed at the data source. The name of the stored procedure. You can use the Parameters property of a command to access input and output parameters and return values, regardless of which Execute method is called. When using ExecuteReader, return values and output parameters will not be accessible until the DataReader is closed. The name of a table.
16

Text Stored Procedure

TableDirect

Command Execution


Command execution return values.

Method ExecuteReader ExecuteScalar ExecuteNonQuery ExecuteXMLReader

Return Value Returns a DataReader object Returns a single scalar value. Executes a command that does not return any rows. Returns an XmlReader. Available for a SqlCommand object only.

17

Querying Data
 

By using a SQL select command, you can retrieve a data set for viewing. To accomplish this with a SqlCommand object, you would use the ExecuteReader method, which returns a SqlDataReader object.

18

Inserting Data


To insert data into a data base, use the ExecuteNonQuery method of the SqlCommand object.

19

Updating Data


The ExecuteNonQuery method is also used for updating data.

20

Deleting Data


You can also delete data using the ExecuteNonQuery method.

21

Getting single values




Sometimes all you need from a data base is a single value, which could be a count, sum, average or other aggregated value from a data set. Performing an ExecuteReader and calculating the result in your code is not the most efficient way to do this. The best choice is to let the data base perform the work and return just the single value you need.

22

Getting single values Sample Code

23

The SQL DataReader Object




The DataReader object allows you to obtain the results of a SELECT statement from a command object. The data returned from a DataReader is a forward-only stream of data. This means that you can only pull the data from the stream in a sequential manner. The ExecuteReader method of the SqlCommand object, returns a SqlDataReader instance.

24

Reading Data


To read the data from DataReader, you must pull data from a table row-by-row. Once a row has been read, the previous row is no longer available. To read that row again, you would have to create a new instance of the SqlDataReader and read through the data stream again.

25

Reading Data Sample code

26

Output

27

Working with disconnected data




 

A DataSet is an in-memory data store that can hold numerous tables. DataSet only hold data and do not interact with a data source. It is the SqlDataAdapter that manages Connections with the data source and gives us disconnected behavior. The SqlDataAdapter opens a connection only when required and closes it as soon as it has performed its task.

SqlDataAdapter tasks:
SqlDataAdapter performs the following tasks when filling a DataSet with data:
Open Connection Execute SELECT Command Close Connection

performs the following actions when updating data source with DataSet changes:
Open Connection Execute UPDATE Command Close Connection

28

The DataSet Object


 

DataSet objects are in-memory representations of data. They contain multiple DataTable objects, which contain columns and rows, just like normal data base tables. You can even define relations between tables to create parentchild relationships. The DataSet is specifically designed to help manage data in memory and to support disconnected operations on data, when such a scenario make sense. The DataSet constructor doesn't require parameters. However there is one overload that accepts a string for the name of the DataSet, which is used if you were to serialize the data to XML.
29

DataSet

*Source from msdn

30

The SQL DataAdapter Object




The DataAdapter fills a DataSet object when reading the data and writes in a single batch when persisting changes back to the data base. A DataAdapter contains a reference to the Connection object and opens and closes the connection automatically when reading from or writing to the data base. The DataAdapter contains Command object references for SELECT, INSERT, UPDATE, and DELETE operations on the data.

31

Creating A SQL DataAdapter




The SqlDataAdapter holds the SQL commands and Connection object for reading and writing data. You initialize it with a SQL SELECT statement and Connection object. The SqlDataAdapter contains all of the commands necessary to interact with the data source. It is the SqlDataAdapter's responsibility to open and close the Connection during Fill and Update method calls.

32

Filling the DataSet




The DataSet must be instantiated before trying to Fill it with data. The second parameter is the name of the Table that will be created in the DataSet. You can name the Table anything you want. Its purpose is so you can identify the Table with a meaningful name later on.

 

33

Sample Code

34

Output

35

Adding parameters to Command


 

Command Object allows you to add parameters at runtime. Anything placed into a parameter will be treated as field data, not part of the SQL statement, which makes your application much more secure. Using parameterized queries is a three step process:  Construct the SqlCommand command string with parameters.  Declare a SqlParameter object, assigning values as appropriate.  Assign the SqlParameter object to the SqlCommand object's Parameters property.
36

Working with Parameters

37

Working with Stored Procedures


 

Stored procedures can accept data as input parameters and can return data as output parameters, result sets. Stored Procedure Code:

38

Sample Code

39

Sample Code

40

Sample Code

41

Exercises
1. 2. Design a Windows based application which connects to the Database and to display the data on the screen in a DataGrid Control. Design a windows based application to connect to the Database and Display the First Record on the screen in Textboxes. 1. Implement the Record Navigation with command buttons. 2. Display the proper warning messages while navigating. Add the following action buttons to the existing application: a) Add New Record b) Edit Existing Record c) Delete Record d) Show total no of Records e) Implement Exception Handling for each section of the Application Design a Windows based application to work with stored procedures. 1. Stored procedures should contain input and output parameters Design a Windows based application to implement database transactions programmatically.

3.

4. 5.

42