Chapter 3:


Published on

ជំពូកទី៣ នៃមុខវិជ្ជា Advanced C#

Published in: Education
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Chapter 3:

  1. 1. Advanced ProgrammingMethodology in C# -Database
  2. 2. ADO.NET
  3. 3. IntroductionBefore .NET, developers used data access technologiessuch as ODBC, OLE DB, and ActiveX Data Object(ADO). With the introduction of .NET, Microsoft createda new way to work with data, called ADO.NET.ADO.NET is a set of classes exposing data accessservices to .NET programmers, providing a rich setof components for creating distributed, data-sharingapplications. ADO.NET is an integral part of the.NET Framework and provides access to relational,XML, and application data.
  4. 4. Introductions (Cont.)ADO.NET classes are found in System.Data.dll.This technology supports a variety ofdevelopment needs, including the creation offront-end database clients and middle-tierbusiness objects used by applications, tools,languages, and Internet browsers. Hence,ADO.NET helps connect the UI, or presentationlayer, of your application with the data source ordatabase.
  5. 5. ADO.NET and .NET Base ClassLibraryA data set (a DataSet object) can hold largeamounts of data in the form of tables (DataTableobjects), their relationships (DataRelationobjects), and constraints (Constraint objects) inan in-memory cache, which can then beexported to an external file or to another dataset. Since XML support is integratedinto ADO.NET, you can produce XML schemasand transmit and share data using XMLdocuments.
  6. 6. ADO.NET and .NET Base ClassLibrary (Cont.)
  7. 7. ADO.NET ArchitectureADO.NET offers two types of architectural componentsto build data-centric applications: connectedand disconnected. Within Microsoft .NET Framework,ADO.NET is housed in the namespaceSystem.Data (the assembly name is System.Data.dll), soall the classes and functions for connected anddisconnected components live in the same namespace.Hence, it is important to add a reference ofSystem.Data to your application irrespective of theconnected or disconnected architecture style youhave chosen or will choose later.
  8. 8. ADO.NET Architecture (Cont.)
  9. 9. Connected Data ObjectsADO.NET’s connected architecture relies on aconsistent database connection to access data andperform any operations on the retrieved data. ADO.NEToffers the following objects to help you build yourapplication with a connected architecture:• Connection• Command• DataReader
  10. 10. ConnectionBefore you can do anything useful with a database, youneed to establish a session with the database server.You do this with an object called a connection. Herebelow are data providers that provided by Microsoft:
  11. 11. Connection (Cont.)String connString = string.Empty;connString = “server = sqlexpress; integrated security =true”; // Window AuthenticationconnString = “server = sqlexpress; user id = sa;password = 1234567”; // SQL AuthenticationSqlConnection conn = new SqlConnection(connString);Conn.Open();//// Code//Conn.Close();
  12. 12. CommandOnce you’ve established a connection tothe database, you want to start interactingwith it and getting it doing somethinguseful for you. You may need to retrieve,add, update, or delete some data, orperhaps modify the database in someother way, usually by running a query.Whatever the task, it will inevitably involvea command.
  13. 13. Command (Cont.)
  14. 14. Command (Cont.)Commands aren’t much use unless you can executethem, so let’s look at that now. Commands have severaldifferent methods for executing SQL. The differencesbetween these methods depend on the results youexpect from the SQL. Queries return rows of data(result sets), but the INSERT, UPDATE, and DELETEstatements don’t.
  15. 15. DataReaderA data reader is a fast, unbuffered,forward-only, read-only connectedstream that retrieves data on a per-row basis. It reads one row at a time asit loops through a result set. You can’tdirectly instantiate a data reader;instead, you create one with theExecuteReader method of a command.
  16. 16. DataReader (Cont.)// Connection stringString connString = @"server=.sql2012;database=AdventureWorks;IntegratedSecurity=SSPI";// Querystring sql = @"select Name from Production.Product";// Create connectionSqlConnection conn = new SqlConnection(connString);// Open connectionconn.Open();
  17. 17. DataReader (Cont.)// Create commandSqlCommand cmd = new SqlCommand(sql, conn);// Create data readerSqlDataReader rdr = cmd.ExecuteReader();// Loop through result setwhile (rdr.Read()){ // Add to listbox - one row at a time lbxProduct.Items.Add(rdr[0]);}// Close data readerrdr.Close();conn.Close();
  18. 18. Disconnected Data ObjectsADO.NET’s disconnected architecture offers flexibleapplication design and helps organizations savedatabase connections. Hence, data can be retrievedand then stored locally on the device in the form of aDataSet object. The retrieved DataSet can be modifiedby users on their local devices such as laptops,handhelds, tablets, and so on, and once that’s done,they can sync the changes into the central data source.Disconnected architecture utilizes expansive resourceslike Connection in a very optimum way (that is, to openlate and close early).
  19. 19. Disconnected Data Objects (Cont.)ADO.NET offers the following objects to help you buildyour application with a disconnected architecture:• DataSet• DataAdapter• DataTable• DataColumn• DataRow
  20. 20. DataSetyou’ll look at a new object for accessing data,the data set. Unlike data readers; a distinctADO.NET component used by all data providers.Data sets are completely independent of andcan be used either connected to ordisconnected from data sources. Theirfundamental purpose is to provide a relationalview of data stored in an in-memory cache.
  21. 21. DataSet (Cont.)
  22. 22. DataSet vs DataReaderIf you simply want to read and display data,then you need to use only a data reader, asyou saw in the previous chapter,particularly if you’re working with largequantities of data. In situations where youneed to loop through thousands or millionsof rows, you want a fast sequential reader(reading rows from the result set one at atime), and the data reader does this job inan efficient way.
  23. 23. DataSet vs DataReader (Cont.)If you need to manipulate the data in any wayand then update the database, you need to usea data set. A data adapter fills a data set byusing a data reader; additional resources areneeded to save data for disconnected use. Youneed to think about whether you really need adata set; otherwise, you’ll just be wastingresources. Unless you need to update the datasource or use other data set features such asreading and writing to XML files, exportingdatabase schemas, and creating XML views of adatabase, you should use a data reader.
  24. 24. DataAdapterWhen you first instantiate a data set, it contains nodata. You obtain a populated data set by passing it toa data adapter, which takes care of connection detailsand is a component of a data provider. A data set isn’tpart of a data provider. It’s like a bucket, ready to befilled with water, but it needs an external pipe to let thewater in. In other words, the data set needs a dataadapter to populate it with data and to support accessto the data source. Each data provider has its own dataadapter in the same way that it has its own connection,command, and data reader.
  25. 25. DataAdapter (Cont.)
  26. 26. DataAdapter (Cont.)The data adapter constructor is overloaded. You canuse any of the following to get a new data adapter.We’re using the SQL Server data provider, but theconstructors for the other data providers areanalogous.SqlDataAdapter da = new SqlDataAdapter();SqlDataAdapter da = new SqlDataAdapter(cmd);SqlDataAdapter da = new SqlDataAdapter(sql, conn);SqlDataAdapter da = new SqlDataAdapter(sql, connString);
  27. 27. DataAdapter (Cont.)So, you can create a data adapter in four ways:• You can use its parameterless constructor (assigning SQL and the connection later).• You can pass its constructor a command (here, cmd is a SqlCommand object).• You can pass a SQL string and a connection.• You can pass a SQL string and a connection string.
  28. 28. DataSet with DataAdapter// Connection stringstring connString = @"server=sqlexpress;database=AdventureWorks; Integrated Security=true";// Querystring sql = @"select Name,ProductNumberfrom Production.Product where SafetyStockLevel > 600";// Create connectionSqlConnection conn = new SqlConnection(connString);// Open connectionconn.Open();
  29. 29. DataSet with DataAdapter (Cont.)// Create Data AdapterSqlDataAdapter da = new SqlDataAdapter(sql, conn);// Create DatasetDataSet ds = new DataSet();// Fill Datasetda.Fill(ds, "Production.Product");// Display datagvProduct.DataSource = ds.Tables["Production.Product"];//Connection closeconn.Close();
  30. 30. DataTableA data table is an instance of the classSystem.Data.DataTable. It’s conceptually analogous to arelational table. You can access these nested collectionsvia the Rows and Columns properties of the data table.A data table can represent a stand-alone independenttable, either inside a data set, as you’ll see in thischapter, or as an object created by another method, asyou saw in the previous chapter when a data table wasreturned by calling the GetSchemaTable method on adata reader.
  31. 31. DataTable (Cont.)DataTable table = new DataTable("ParentTable");DataColumn column;DataRow row;column = new DataColumn();column.DataType = System.Type.GetType("System.Int32");column.ColumnName = "id";column.ReadOnly = true;column.Unique = true;table.Columns.Add(column);
  32. 32. DataTable (Cont.)column = new DataColumn();column.DataType = System.Type.GetType("System.String");column.ColumnName = "ParentItem";column.AutoIncrement = false; column.Caption = "ParentItem"; column.ReadOnly = false;column.Unique = false; table.Columns.Add(column);DataColumn[] PrimaryKeyColumns = new DataColumn[1];PrimaryKeyColumns[0] = table.Columns["id"];table.PrimaryKey = PrimaryKeyColumns;
  33. 33. DataTable (Cont.)dataSet = new DataSet();dataSet.Tables.Add(table);for (int i = 0; i<= 2; i++){ row = table.NewRow(); row["id"] = i; row["ParentItem"] = "ParentItem " + i; table.Rows.Add(row);}
  34. 34. DataColumnA data column represents the schema of a columnwithin a data table and can then be used to set or getcolumn properties. For example, you could use it to setthe default value of a column by assigning a value tothe DefaultValue property of the data column. Youobtain the collection of data columns using the datatable’s Columns property, whose indexer accepts eithera column name or a zero-based index, for example(where dt is a data table):DataColumn col = dt.Columns["ContactName"];DataColumn col = dt.Columns[2];
  35. 35. DataRowA data row represents the data in a row. You canprogrammatically add, update, or delete rows ina data table. To access rows in a data table, youuse its Rows property, whose indexer accepts azero-based index, for example (where dt is adata table):DataRow row = dt.Rows[2];
  36. 36. Understanding .NET DataProvidersADO.NET consists of various data providers that allowan easy and predefined object model to communicatewith various industry databases such as SQL Server,Oracle, Microsoft Access, and many others.
  37. 37. Understanding .NET DataProvidersFor example, if you use SQL Server, you should use theSQL Server data provider (System.Data.SqlClient)because it’s the most efficient way to access SQLServer. The OLE DB data provider supports access toolder versions of SQL Server as well as to otherdatabases, such as Access, DB2, MySQL, and Oracle.However, native data providers (such asSystem.Data.OracleClient) are preferable forperformance, since the OLE DB data provider worksthrough two other layers, the OLE DB servicecomponent and the OLE DB provider, before reachingthe data source.
  38. 38. Understanding .NET DataProviders
  39. 39. Understanding .NET DataProvidersEach .NET data provider is designed to do the followingtwo things very well:• Provide access to data with an active connection tothe data source• Provide data transmission to and from disconnecteddata sets and data tables
  40. 40. Understanding .NET DataProvidersDatabase connections are established by using the dataprovider’s Connection class (for example,System.Data.SqlClient.SqlConnection). Othercomponents such as data readers, commands, and dataadapters support retrieving data, executing SQLstatements, and reading or writing to data sets or datatables, respectively.
  41. 41. Understanding the SQL Server DataProviderThe .NET data provider for SQL Server is in theSystem.Data.SqlClient namespace. Although you canuse System.Data.OleDb to connect with SQL Server,Microsoft has specifically designed theSystem.Data.SqlClient namespace to be used with SQLServer, and it works in a more efficient and optimizedway than System.Data.OleDb. The reason for thisefficiency and optimized approach is that this dataprovider communicates directly with the server usingits native network protocol instead of through multiplelayers.
  42. 42. Commonly Used SqlClient Classes
  43. 43. Understanding the OLE DB Data Provider• Outside .NET, OLE DB is still Microsoft’s high-performance data access technology.• You can use this data provider to access data stored inany format, so even in ADO.NET it plays an importantrole in accessing data sources that don’t have their ownADO.NET data providers.
  44. 44. Commonly Used OleDb Classes
  45. 45. Understanding the ODBC Data Provider• ODBC was Microsoft’s original general-purpose data accesstechnology.• The ODBC architecture is essentially a three-tier process. Anapplication uses ODBC functions to submit database requests.ODBC converts the function calls to the protocol (call-levelinterface) of a driver specific to a given data source. The drivercommunicates with the data source, passing any results or errorsback up to ODBC. Obviously, this is less efficient than a database-specific data provider’s direct communication with a database,so for performance it’s preferable to avoid the ODBC dataprovider, since it merely offers a simpler interface to ODBC butstill involves all the ODBC overhead.
  46. 46. Commonly Used Odbc Classes
  47. 47. SummaryThis chapter you will understand about two main typesof data access that provided from ADO.NET; ConnectedData Objects and Disconnected Data Objects. Bothtypes have their own advantages to fulfill the full-functionality to access data. Both types their own maincomponents.• Connected Data Objects : Connection, Command, and DataReader.• Disconnected Data Objects : DataSet, DataAdapter, DataTable, DataColumn and DataRow.