Ch06 ado.net fundamentals

1,031 views
936 views

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,031
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
56
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Ch06 ado.net fundamentals

  1. 1. ADO.NET FUNDAMENTALS Desktop and web applications are data-driven. These applications are largely concerned with retrieving,displaying, and modifying data. The .NET Framework includes its own data access technology:ADO.NET. ADO.NET consists of managed classes that allow .NET applicationsto connect to data sources, execute commands, and managedisconnected data. In ASP.NET, there are a few ways to get information out of adatabase without directly using the ADO.NET classes.  The SqlDataSource control  LINQ to SQL 1  Profiles:
  2. 2. The ADO.NET Architecture ADO.NET uses a multilayered architecture that revolves around afew key concepts, such as Connection, Command, and DataSetobjects. Differences between ADO.NET and some other databasetechnologies is how it deals with the challenge of different datasources In classic ADO, programmers use a generic set of objects no matterwhat the underlying data source is. ADO.NET, which uses a data provider model. 2
  3. 3. ADO.NET Data Providers A data provider is a set of ADO.NET classes that allows you to access a specificdatabase, execute SQL commands, and retrieve data. Essentially, a data provider is a bridge between your application and a datasource. The classes that make up a data provider include the following:  Connection : Used to establish a connection to a data source.  Command : Used to execute SQL commands and stored procedures.  DataReader : This object provides fast read-only, forward-only access to the data retrieved from a query.  DataAdapter : Use it to fill a DataSet (a disconnected collection of tables and relationships) with information extracted from a data source and apply changes to a data source. 3
  4. 4. ADO.NET Data Providers cont.. ADO.NET doesn’t include generic data provider objects. Instead, it includes different data providers specifically designedfor different types of data sources. Each data provider has a specific implementation of theConnection, Command, DataReader, and DataAdapter classes that’soptimized for a specific RDBMS. For example, to create a connection to a SQL Server database, usea connection class named SqlConnection. ADO.NET provider model is that it’s extensible, developers cancreate their own providers for proprietary data sources 4
  5. 5. ADO.NET Data Providers cont..The .NET Framework is bundled with a small set of four providers: SQL Server provider: Provides optimized access to a SQL Serverdatabase (version 7.0 or later). OLE DB provider: Provides access to any data source that has anOLE DB driver. This includes SQL Server databases prior to version7.0. Oracle provider: Provides optimized access to an Oracle database(version 8i or later). ODBC provider: Provides access to any data source that has anODBC driver.5
  6. 6. ADO.NET Data Providers cont.. Figure shows the layers of the ADO.NET provider model6 6
  7. 7. SQL Server 2005 ADO.NET provides support for a few features that arelimited to SQL Server 2005  MARS (multiple active result sets)  User-defined data types  Managed stored procedures  SQL notifications  Snapshot transaction isolation 7
  8. 8. Fundamental ADO.NET ClassesADO.NET has two types of objects: connection-based and content-based.Connection-based objects : Data provider objects such as Connection, Command, DataReader, andDataAdapter. Allows to connect to a database, execute SQL statements, move througha read-only result set, and fill a DataSet. Specific to the type of data source, and found in a provider-specificnamespaceContent-based objects: Objects are really just “packages” for data Include DataSet, DataColumn, DataRow, DataRelation, and severalothers. 8
  9. 9. Fundamental ADO.NET Classes cont.. The ADO.NET NamespacesNamespace DescriptionSystem.Data Contains the key data container classes that model columns, relations,tables, datasets, rows, views, and constraintsSystem.Data.Common Contains base, mostly abstract classes that implement some of the interfaces from System.Data and define the core ADO.NET functionalitySystem.Data.OleDb Contains the classes used to connect to an OLE DB providerSystem.Data.SqlClient Contains the classes you use to connect to a Microsoft SQL Server databaseSystem.Data. Contains the classes required to connect to an Oracle databaseOracleClientSystem.Data.Odbc Contains the classes required to connect to most ODBC driversSystem.Data.SqlTypes Contains structures that match the native data types in SQL 9 Server.
  10. 10. The Connection Class The Connection class allows you to establish a connection to thedata source. Before accessing database need to establish database connection. The core Connection properties and methods are specified by theIDbConnection interface, which all Connection classes implement. Connection Strings : When you create a Connection object, youneed to supply a connection string.  The server where the database is located  The database you want to use  How the database should authenticate you. 10
  11. 11. The Connection Class cont.. For examplestring connectionString = "Data Source=localhost; Initial Catalog=Northwind;" + "Integrated Security=SSPI“; For a newly installed SQL Server database, the sa (system administrator) accountis usually presentstring connectionString = "Data Source=localhost; Initial Catalog=Northwind;" + "user id=sa; password=opensesame"; If you’re using the OLE DB provider, string must provider settingstring connectionString = "Data Source=localhost; Initial Catalog=Sales;" + "user id=sa; " + password=da#ta_li#nk_43;Provider=MSDAORA";For access database:-string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=C:DataSourcesNorthwind.mdb"; 11
  12. 12. The Connection Class cont.. Don’t hard-code a connection string. <connectionStrings> section of the web.config file is a handy place to store yourconnection. Here’s an example <configuration> <connectionStrings> <add name="Northwind" connectionString= "Data Source=localhost; Initial Catalog=Northwind; Integrated Security=SSPI"/> </connectionStrings> ... </configuration> Retrieve your connection string by name from theWebConfigurationManager.ConnectionStrings collection string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;Note : Import the System.Web.Configuration namespace. 12
  13. 13. Testing a ConnectionTo use this code as written, you must import the System.Data.SqlClient namespace// Create the Connection object.string connectionString =WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;SqlConnection con = new SqlConnection(connectionString);try{ con.Open(); lblInfo.Text = "<b>Server Version:</b> " + con.ServerVersion; lblInfo.Text += "<br /><b>Connection Is:</b> " + con.State.ToString();}catch (Exception err){ lblInfo.Text = "Error reading the database. " + err.Message;}finally{ con.Close(); lblInfo.Text += "<br /><b>Now Connection Is:</b> " + 13 con.State.ToString();}
  14. 14. Connection Pooling Connections are a limited server resource. (open the connection aslate as possible and release it as quickly as possible.) Acquiring a connection takes a short, but definite, amount of time,becomes a overhead, affects scalability of web application One solution is connection pooling. Connection pooling is the practiceof keeping a permanent set of open database connections Connection pools in ADO.NET are completely transparent to theprogrammer.ADO.NET does not include a connection pooling mechanism. However,most ADO.NET providers implement some form of connection pooling.The SQL Server and Oracle data providers implement their ownefficient connection pooling algorithms. 14
  15. 15. Connection Pooling cont…Setting DescriptionMax Pool Size Max. no. of pools allowed in the pool(default to 100).If max no. reached, any further attempts to open conn are queued until conn becomes availableMin Pool Size The minimum number of connections always retained the pool(default to 0).Pooling When true, conn is drawn from appropriate pool, or if necessary ,is created and added to appropriate pool.Connection Lifetime Specifies time interval in seconds.We can put these settings in connection string in key/value pair. 15
  16. 16. The Command and DataReader Classes The Command class allows you to execute any type ofSQL statement. can use a Command class to perform data definitiontasks, but much more likely to perform data manipulationtasks. The provider-specific Command classes implementstandard functionality, like connection classes. The IDbCommand interface defines a few key propertiesand the core set of methods that are used to execute acommand over an open connection. 16
  17. 17. Command Basics Before you can use a command,  Choose the command type  Set the command text  Bind the command to a connection  Pass the information needed depending upon command type Values for the CommandType Enumeration Value Description CommandType.Text The command will execute a direct SQL statement. CommandText property provides SQL statement CommandType. The command will execute a stored procedure in the StoredProcedure data source. The CommandText property provides the name of the stored procedure. CommandType. The command will query all the records in the table. TableDirect The CommandText is the name of the table from which 17 the command will retrieve the records.
  18. 18. Command Basics cont..For example, here’s how you would create a Command object that represents aquery. SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM Employees";More efficient way, use one of the Command constructors SqlCommand cmd = new SqlCommand(“select * FROM Employees“, con);Alternatively, to use a stored procedure, SqlCommand cmd = new SqlCommand("GetEmployees", con); cmd.CommandType = CommandType.StoredProcedure; 18
  19. 19. Command object… The Command object provides three methods that you can use toperform the command. Command Methods: Method Description ExecuteNonQuery() Executes non-SELECT commands, such as SQL commands that insert, delete, or update records. ExecuteScalar() Executes a SELECT query and returns the value of the first field of the first row from the rowset generated by the command. ExecuteReader() Executes a SELECT query and returns a DataReader object that wraps a read-only, forward-only cursor. 19
  20. 20. The DataReader Class A DataReader allows you to read the data returned by a SELECTcommand one record at a time, in a forward-only, read-only stream. Sometimes called a firehose cursor. Using a DataReader is the simplest way to get to your data, but it lacksthe sorting and relational abilities of the disconnected DataSet Core methods of the DataReader  Read()  GetValue()  GetValues()  GetInt32(),GetChar(),GetDateTime(), GetXxx()  NextResult()  Close() 20
  21. 21. The DataReader Class cont..The following example creates a simple query command to return all therecords from the Employees table.protected void Page_Load(object sender, EventArgs e){ // Create the Command and the Connection objects. string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"]. ConnectionString; SqlConnection con = new SqlConnection(connectionString); string sql = "SELECT * FROM Employees"; SqlCommand cmd = new SqlCommand(sql, con); ... // Open the Connection and get the DataReader. con.Open(); SqlDataReader reader = cmd.ExecuteReader(); 21 ...
  22. 22. The DataReader Class cont.. The ExecuteReader() method has an overloaded version that takesone of the values from the CommandBehavior enumeration as aparameter. One useful value is CommandBehavior.CloseConnection. When you pass this value to the ExecuteReader() method, theDataReader will close the associated connection as soon as you closethe DataReader. SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // (Build the HTML string here.) // No need to close the connection. You can simply close the reader. reader.Close(); ….. 22
  23. 23. Processing Multiple Result Sets The command you execute can return a multiple result sets. A command can return more than one result set in two ways:  If you’re calling a stored procedure, it may use multiple SELECT statements  If you’re using a straight text command, you may be able to batch multiple commands by separating commands with a semicolon (;)  Here’s an example string sql = "SELECT TOP 5 * FROM Employees;" + "SELECT TOP 5 * FROM Customers; SELECT TOP 5 * FROM Suppliers“ Initially DataReader provides access from the Employees table. Once you’ve finished using the Read() method to read all these records, you cancall NextResult() to move to the next result set. 23
  24. 24. The ExecuteScalar() Method The ExecuteScalar() method returns the value stored in the first field ofthe first row of a result set generated by the command’s SELECT query. Usually used to execute a query that retrieves only a single field, perhapscalculated by a SQL aggregate function such as COUNT() or SUM(). For Example SqlConnection con = new SqlConnection(connectionString); string sql = " SELECT COUNT(*) FROM Employees "; SqlCommand cmd = new SqlCommand(sql, con); // Open the Connection and get the COUNT(*) value. con.Open(); int numEmployees = (int)cmd.ExecuteScalar(); con.Close(); // Display the information. HtmlContent.Text += "<br />Total employees: <b>" + numEmployees.ToString() + "</b><br />"; 24
  25. 25. The ExecuteNonQuery() Method The ExecuteNonQuery() method executes commands that don’t return a resultset, such as INSERT, DELETE, and UPDATE. The ExecuteNonQuery() method returns a single piece of information—thenumber of affected records Here’s an example: SqlConnection con = new SqlConnection(connectionString); string sql = "DELETE FROM Employees WHERE EmployeeID = “ + empID.ToString(); SqlCommand cmd = new SqlCommand(sql, con); try { con.Open(); int numAff = cmd.ExecuteNonQuery(); HtmlContent.Text = “Number of Records affected” + numAff.toString(); } catch (SqlException exc) { } finally { 25 con.Close(); }
  26. 26. Using Parameterized Commands A parameterized command is simply a command that usesplaceholders in the SQL text. The placeholders indicate dynamically supplied values, which arethen sent through the Parameters collection of the Command object. For example, SELECT * FROM Customers WHERE CustomerID = ALFKI It would become something like this: SELECT * FROM Customers WHERE CustomerID = @CustID3 The placeholders are then added separately and automaticallyencoded. 26
  27. 27. Calling Stored Procedures A stored procedure is a batch of one or more SQL statementsthat are stored in the database. Stored procedures are similar to functions in that they arewell-encapsulated blocks of logic that can accept data (throughinput parameters) and return data. Stored procedures have many benefits:  They are easier to maintain. They allow you to implement more secure database usage They can improve performance 27
  28. 28. Calling Stored Procedures cont..Here’s the SQL code needed to create a stored procedure for inserting a single record intothe Employees table IF EXISTS (SELECT name FROM sysobjects WHERE name = InsertEmployee AND type = P) DROP PROCEDURE InsertEmployee GO CREATE PROCEDURE InsertEmployee @TitleOfCourtesy varchar(25), @LastName varchar(20), @FirstName varchar(10), @EmployeeID int OUTPUT AS INSERT INTO Employees (TitleOfCourtesy, LastName, FirstName, HireDate) VALUES (@TitleOfCourtesy, @LastName, @FirstName, GETDATE()); SET @EmployeeID = @@IDENTITY 28
  29. 29. Calling Stored Procedures cont..Next, you can create a SqlCommand to wrap the call to the stored procedure. string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString; SqlConnection con = new SqlConnection(connectionString); // Create the command for the InsertEmployee stored procedure. SqlCommand cmd = new SqlCommand("InsertEmployee", con); cmd.CommandType = CommandType.StoredProcedure;Now add the stored procedure’s parameters to the Command.Parameters collection. cmd.Parameters.Add(new SqlParameter("@TitleOfCourtesy", SqlDbType.NVarChar, 25)); cmd.Parameters["@TitleOfCourtesy"].Value = title; cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 20)); cmd.Parameters["@LastName"].Value = lastName; cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 10)); cmd.Parameters["@FirstName"].Value = firstName;The last parameter is an output parameter. cmd.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 4)); cmd.Parameters["@EmployeeID"].Direction = ParameterDirection.Output; 29
  30. 30. Calling Stored Procedures cont..ADDING PARAMETERS WITH IMPLICIT DATA TYPES: One handy shortcut is the AddWithValue() method ofthe Parameters collection. This method takes the parameter name and the valuebut no data type information. It infers the data type from the supplied data. Here’s an example: cmd.Parameters.AddWithValue("@LastName", lastName); cmd.Parameters.AddWithValue("@FirstName" firstName); 30

×