Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 80 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
80
Dung lượng
1,44 MB
Nội dung
i 430234 Ch07.qxd 7/1/03 9:01 AM Page 288 289 Previous chapters covered many of the basic elements of Visual Studio .NET, the .NET Framework, ASP.NET Web Forms, and controls. These chapters were intended to provide enough of a .NET foundation to get to the core of most applications: data access. Data access is an important factor in most ASP.NET applications. The .NET Framework includes ADO.NET, which provides access to data in many loca- tions. ADO.NET is not just another version of ADO; it represents a complete paradigm shift in data retrieval and manipulation. ADO.NET is a set of classes to work with data. ADO.NET supports unstruc- tured, structured, hierarchical, and relational data storage, which allows access to data wherever it is. It has a consistent object model, so learning how to retrieve and manipulate data in one data source is similar to working with most other data sources. Many companies have already embraced XML in some form. Being able to integrate XML data was a primary design constraint of ADO.NET. Integration between ADO.NET and XML is done at with many levels, with ADO.NET being able to use many of the XML classes that are built into the .NET Frame- work. This allows for seamless use of ADO.NET to read and write XML data. Data Access with ADO.NET CHAPTER 8 j 430234 Ch08.qxd 7/1/03 9:01 AM Page 289 This chapter starts by comparing connected and disconnected data, and then covers the primary ADO.NET objects, looking at many details and examples. After covering the objects, this chapter covers different methods of performing data manipulation, sorting, and filtering using the DataGrid control. Classroom Q & A Q: Is it possible to load and save data as XML using ADO.NET? A: Absolutely. ADO.NET represents a major change to ADO; ADO.NET is much more XML-centric than past versions of ADO. Q: I heard that ADO.NET is focused on disconnected data. Is there a way to get connected data? A: Yes. ADO.NET is indeed focused around disconnected data, but ADO.NET has limited support for connected data via a read-only, forward-only result set. This will be covered in more detail in this chapter. Q: Can the DataGrid be used to add, delete, and edit the data? A: Yes. This chapter will take a close look the DataGrid in detail, and you will see how the DataGrid can give you everything you’re look- ing for. Connected versus Disconnected Data Previous versions of ADO were connection-centric, meaning that most of the data functionality was exposed via a maintained connection to the database. ADO supported disconnected recordsets and Remote Data Objects (RDO), but this certainly was not the focus of ADO. One problem that is associated with connected data is that any data that is accessed will potentially create locks on rows in the database. Depending on the type of lock, user access to a given row may be paused while waiting for a lock to free up. Row locking at the database can be the cause of many perfor- mance and scalability problems. ADO.NET is a disconnected-data-centric. Disconnected data retrieves the data from the data store and then closes the connection. One advantage of this model is that the data can be downloaded to the client, the connection can be closed, and the user can work with the data while offline. Updates can be sent back to the server when appropriate. 290 Chapter 8 j 430234 Ch08.qxd 7/1/03 9:01 AM Page 290 One of the problems with working with disconnected data is that changes can be made to the data from multiple locations at the same time, and when it comes time to update the data at the data store, concurrency errors may take place. ADO.NET provides the ability to deal with concurrency issues in a clean fashion. ADO.NET Data Providers Adata provider supplies a bridge from the application to the data source. Think of the data provider as a set of drivers that are specific to a data store. Different providers include those discussed in the following subsections. SQL Data Provider The SQL Server .NET data provider contains classes that provide functionality that is similar to the generic OleDb data provider, but these classes are tuned for SQL Server data access. Although the OleDb data provider can be used to access SQL Server, the SQL data provider is the recommended data provider for SQL Server 7.0+ data access. The prefix for SQL provider objects is Sql, so a connection is a SqlConnection class. OleDb Data Provider The OleDb data provider contains classes for general-purpose access to many data sources, such as SQL Server 6.5 and earlier, Oracle, SyBase, DB2/400, and Microsoft Access. The prefix for OleDb provider objects is OleDb, so a connec- tion is an OleDbConnection class. Odbc Data Provider The Odbc data provider contains classes for access to SQL Server, Oracle, and Access. The ODBC provider is available via free download from the Microsoft Solution Developer Network (MSDN) Web site at http://msdn.microsoft.com/ downloads/sample.asp?url=/msdn-files/027/001/668/msdncompositedoc.xml. To use ODBC, download and install the ODBC provider, and then add a ref- erence to the Microsoft.Data.ODBC.dll file. The prefix for ODBC provider objects is Odbc, so a connection is an OdbcConnection class. Oracle Data Provider The Oracle data provider contains classes for access to Oracle 8i+ database servers. The Oracle provider is available for free download from the Data Access with ADO.NET 291 j 430234 Ch08.qxd 7/1/03 9:01 AM Page 291 MSDN Web site at http://msdn.microsoft.com/downloads/sample.asp?url=/ MSDN-FILES/ 027/001/940/msdncompositedoc.xml. To use the Oracle data provider, download and install the provider and add a reference to the System.Data.OracleClient.dll file. The prefix for Oracle provider is Oracle, so a conection is an OracleConnection. ADO.NET Data Namespaces The .NET Framework is divided into logical namespaces. ADO.NET has its own logical namespaces and extends some of the existing .NET Framework namespaces. Table 8.1 lists most of the available ADO.NET namespaces. When working with these namespaces, a reference must be set to the Sys- tem.Data.dll file and any data provider .dll files. In addition, using the Imports statement as follows can save typing. Imports System.Data Imports System.Data.SqlClient Table 8.1 ADO.NET Namespaces NAMESPACE DESCRIPTION System.Data Provides the main namespace for ADO.NET, which contains many of the primary data classes. System.Data.Common Contains many utility and helper classes that are primarily used by data provider developers. System.Data.SqlClient Contains the SQL Server specific classes for the SQL Server .NET data provider. System.Data.OleDb Contains the OleDb specific classes for the OleDb .NET data provider, which provides access to OleDb specific data sources. System.Data.SqlTypes Provides SQL Server classes that are native to SQL Server. Explicitly creating instances of these classes when accessing SQL results in faster and cleaner code. System.Xml Provides standards-based support for accessing and modifying XML data. Microsoft.Data.ODBC Provides the classes for ODBC specific data access, which allows ODBC access to SQL Server, Oracle, and Access. System.Data.OracleClient Provides the classes for Oracle specific data access. 292 Chapter 8 j 430234 Ch08.qxd 7/1/03 9:01 AM Page 292 Primary Data Objects Several primary data objects are covered in this section. Some of the primary objects are provider specific, while others are not provider specific. The provider-specific data objects, regardless of the provider, provide a core set of functionality, which will be covered in this section. Provider-Specific Data Objects The following data objects are provider specific: the Connection, DataAdapter, Command, Parameter, CommandBuilder, and the DataReader. This means that these objects will have a provider prefix. For example, the SQL Server objects have a SQL prefix, while the OleDb objects have an OleDb prefix. Provider-specific objects are tweaked for that provider, although the objects essentially provide the same functionality. Most of the examples in this section are done with SQL Server using the SQL Server data provider, but the examples can be converted to a different provider by simply changing the provider prefix of the data objects and the connection string. Connection The connection is required to access data in a data store. The connection requires a connection string, which is a list of settings for the connection. Con- nection strings typically identify the name of the computer that has the data store, the user name and password to connect to the data store, and the name of the data store. Additional settings that may be available depending on the type of data store are connection pooling, integrated security, packed size, and protocol. Connection Security Connecting to a data store usually requires security information of some sort, depending on the data store that is being accessed. When SQL Server is installed, it can be set up to use either Windows Authentication or Mixed Mode security. The default setting on SQL Server 2000+ is Windows Authentication. With Windows Authentication, the SQL Server verifies that the user is authenticated based on the user’s Windows login name as well as the Win- dows groups that the user is a member of. There is no separate login to get into SQL Server. Windows Authentication is more secure than Mixed Mode. Win- dow Authentication is also referred to as Trusted Security and Integrated Security. Data Access with ADO.NET 293 j 430234 Ch08.qxd 7/1/03 9:01 AM Page 293 Mixed Mode, which is the default for SQL Server 7 and earlier, is available for situations where SQL Server will be accessed by users who do not have Windows networking accounts. The users who may not have a Windows net- working account includes users who are accessing a non-Microsoft network, such as Novell NetWare. This also includes users who are running SQL Server in a workgroup environment. In situations like this, SQL Server maintains its own list of login names and passwords. In Mixed Mode, SQL Server still allows users to connect using Windows Authentications. Windows Authentication cannot be turned off manually, but it will be off in situations where SQL Server is installed on a Windows 98 or Win- dow ME operating system, which has no support for Windows Authentication. ConnectionString Coming up with a ConnectionString can be the hardest task to accomplish when accessing a data store. The ConnectionString contains the settings for the connection that will be opened to the data store. Every data store supports dif- ferent settings but Table 8.2 names the more common settings. Table 8.2 Typical Connection String Settings SETTING DESCRIPTION Provider (OleDb provider only) Contains the name of the provider that will be used. Think of the provider as the driver for the data store. Connection Timeout Number of seconds to wait for a connection to the data or Connect Timeout store before terminating the attempt for a connection and throwing an exception. Initial Catalog The name of the database. Data Source The name of the computer to be used when accessing data, or the Microsoft Access database full filename. User ID The user name for authentication. Password The password for authentication. Integrated Security or Indicates that the connection will use Windows Trusted Connection Authentication instead of Mide Mode security. Possible values are true, false, and SSPI (SSPI is true). Persist Security Info When set to false, the password and other security information will not be returned as part of the connection if the connection is open or has ever been in an open state. Default is false. 294 Chapter 8 j 430234 Ch08.qxd 7/1/03 9:01 AM Page 294 Although there are many ConnectionString options, a connection may be created by using just a couple of these settings. ConnectionStrings are created by concatenating the name and value settings together, separated by a semi- colon. ConnectionsStrings typically are not case sensitive. Although spaces are supposed to be ignored, it is usually preferable to eliminate all spaces except the space that may be included in some setting names, such as User ID and Workstation ID. Some valid Connection strings follow: ‘Microsoft Access connection Dim cnstr as string = “Provider=Microsoft.Jet.OLEDB.4.0;” cnstr &= “Data Source=C:\Samples\northwind.mdb” This connects to the Microsoft Access database that is located at C:\Samples\ northwind.mdb if security has not been enabled on this database. ‘Microsoft Access connection Dim cnstr as string = “Provider=Microsoft.Jet.OLEDB.4.0;” cnstr &= “Data Source=C:\mypath\nowind.mdb;” cnstr &= “user id=admin;password=hello” This connects to the Microsoft Access database that is located at c:\mypath\ nowind.mdb with the user name of admin and a password of hello. ‘Excel spreadsheet Dim cnstr as string = “Provider=Microsoft.Jet.OLEDB.4.0;” cnstr &= “Data Source=C:\MyExcel.xls;Extended Properties=Excel 8.0;” cnstr &= “HDR=yes” This connects to an Excel spreadsheet using OleDb. The HDR=yes indicates that the first row contains column names of the data. In addition to the connection settings listed in Table 8.2, the SQL Server provider offers the additional settings shown in Table 8.3. As mentioned earlier in this chapter, it is usually preferable to eliminate all spaces except the space that may be included in some setting names, such as User ID and Workstation ID. Some valid SQL Connection strings are as follows: ‘Sql Server Dim cnstr as string = “integrated security=true;database=northwind” This connects to the default instance of SQL Server on the local computer using Windows Authentication connecting to the northwind database. ‘Sql Server Dim cnstr as string = “server=remoteComputer;” cnstr &= “integrated security=true;database=pubs” Data Access with ADO.NET 295 j 430234 Ch08.qxd 7/1/03 9:01 AM Page 295 Table 8.3 SQL Server Provider ConnectionString Settings SQL SERVER SETTING DEFAULT DESCRIPTION Application Name or App .Net SqlClient The name of the current Data Provider application. This is primarily used for logging. If the value is assigned, SQL Server uses this as the name of the process when querying SQL server for active connections (sp_who2 or “Select * from master.dbo.sysprocesses”). Connect Timeout, 15 Number of seconds to wait for a Connection Timeout connection to the data store before or Timeout terminating the attempt for a connection and throwing an exception. Connection Lifetime 0 Used to determine whether a connection should be destroyed. When a connection is returned to the pool, its creation time is compared with the current time and the connection is destroyed if that time span (in seconds) exceeds the value specified by connection lifetime. This option can be useful in clustered configurations to force load balancing between a running server and a server just brought online. Connection Reset true Determines whether the database connection is reset when being removed from the pool. Setting this to false avoids the making of an additional server round trip when obtaining a connection, but the programmer must be aware that the connection state is not being reset. Current Language The SQL Server Language record name. 296 Chapter 8 j 430234 Ch08.qxd 7/1/03 9:01 AM Page 296 Table 8.3 (continued) SQL SERVER SETTING DEFAULT DESCRIPTION Data Source, Server, The name or network address Address, Addr, or of the instance of SQL Server to Network Address which to connect. This setting may also contain the instance name when attempting to connect to a nondefault instance of SQL Server. When empty, this will connect to the default instance of the local SQL Server. Can also be set to “.” (period), “(local),” or “localhost” to select the local machine. Enlist true When true, the pooler automatically enlists the connection in the creation thread’s current transaction context. Encrypt false Set the communications method to encrypted. Initial FileName, The full pathname of the primary file Extended Properties, of an attachable database. If this or AttachDBFileName setting is specified, the Database or Initial Catalog setting must also be specified. OLE DB Services Set this to -4 to disable the automatic pooling of connections. Initial Catalog or Database The name of the database. Integrated Security false Whether the connection is a secure or Trusted_Connection connection. Max Pool Size 100 The maximum number of connections allowed in the pool. Min Pool Size 0 The minimum number of connections allowed in the pool. Network Library or Net ‘dbmssocn’ The network library used to establish a connection to an instance of SQL Server. The default value, dbnssocn, specifies TCP/IP. Other values include dbnmpntw (Named Pipes), dbmsrpcn (Multiprotocol), dbmsadsn (Apple Talk), dbmsgnet (VIA), dbmsipcn (Shared Memory), and dbmsspxn (IPX/SPX). The corresponding network DLL must be installed on the system to which you connect. (continued) Data Access with ADO.NET 297 j 430234 Ch08.qxd 7/1/03 9:01 AM Page 297 [...]...2 98 Chapter 8 Table 8. 3 (continued) SQL SERVER SETTING DEFAULT DESCRIPTION Packet Size 81 92 Size in bytes of the network packets used to communicate with an instance of SQL Server Persist Security Info or PersistSecurityInfo false When set to false, security-sensitive information, such as the password, is not returned as part of the connection if the connection... requiring the use of CType to cast to a particular data type Table 8. 4 lists these methods Table 8. 4 DataReader’s Typed Methods GetBoolean GetByte GetBytes GetChar GetChars GetDataTypeName GetDateTime GetDecimal GetDouble GetFieldType GetFloat GetGuid GetInt16 GetInt32 GetInt64 GetName GetOrdinal GetString GetValue GetValues IsDBNull NextResult GetSchemaTable 307 3 08 Chapter 8 In addition to these helper methods,... deletion The DataTable is bound to DataGrid1 and then a view is created with the RowStateFilter set to display only deleted rows The DataView is then bound to DataGrid2 Figure 8. 8 shows the output 321 322 Chapter 8 Figure 8. 8 The DataGrid controls, which display the deleted rows (top) and the undeleted rows (bottom) Be sure to use the Delete method of the DataRow if changes are going to be sent back... cmd.ExecuteXmlReader() While (dr.Read()) Response.Write(dr(“CustomerID”) & “ - “ _ & dr(“CompanyName”) & “”) End While ‘Cleanup dr.Close() cn.Dispose() cn = Nothing DataReader The DataReader is used to retrieve connected data from the server The DataReader requires a command and connection (see Figure 8. 1) The DataReader returns a forward-only, read-only data stream from a data source This stream represents the... UpdateCommand DeleteCommand DeleteCommand Connection Data Store Figure 8. 4 Multiple DataAdapters to fill multiple DataTables Data Access with ADO.NET DataSet The DataSet is a major component in ADO.NET as an in-memory, relational database The DataSet contains a collection of DataTable objects and a collection of DataRelation objects (see Figure 8. 5) Each DataTable can contain unique and foreign key constraints... The DataRow goes through a series of states that can be viewed and filtered at any time, as shown in Table 8. 5 The RowState can be viewed at any time to determine the current state of a DataRow Figure 8. 7 shows how the RowState changes at different stages of the DataRow’s life 319 320 Chapter 8 Dim dr as DataRow = dt.NewRow( ) RowState = Detached dt.Rows.Add(dr) RowState = Added dt.AcceptChanges( )... Figure 8. 7 The life cycle of a DataRow and its RowState A DataRow can also contain different versions of the data, which can be filtered and viewed using the RowVersion property This can be handy when it’s desirable to look at the deleted or changed rows of a DataTable Table 8. 6 shows the list of available RowVersions This will be covered in more detail in the following sections of this chapter Table 8. 5... UpdateCommand Sql="Select * from orders" DeleteCommand da.SelectCommand.CommandText=Sql Dim dt2 as new DataTable("DataTable2") Connection da.fill(dt2) Data Store Figure 8. 3 DataAdapter being reused to fill multiple DataTables Non-Provider-Specific Data Classes The System.Data namespace provides classes that are not specific to any provider This means that these classes can be used without having connectivity... to the DataAdapter, and the DataAdapter will execute the appropriate command as needed when the DataAdaptor’s Update method is called Figure 8. 4 shows an example of using multiple DataAdapters Updating data sources is covered later in this chapter 309 310 Chapter 8 'fill DataTable1 Sql="Select * from customers" DataTable1 DataTable2 Dim da as new SqlDataAdapter( Sql, cn) Dim dt1 as new DataTable("DataTable1")... word To create a DataReader, use the ExecuteReader method of the Command object The following code is an example of the DataReader 305 306 Chapter 8 Read( ) Display Row( ) NET Data Provider DataReader Connected Data Command Connection Data Store Figure 8. 1 The DataAdapter requires Command and Connection objects Use the Read method to retrieve one row at a time ‘Connection Dim cn As New SqlConnection() . with a password of hello and con- necting to the pubs database with a connection timeout of 30 seconds. 2 98 Chapter 8 j 430234 Ch 08. qxd 7/1/03 9:01 AM Page 2 98 ‘Sql Server Dim cnstr as string. built into the .NET Frame- work. This allows for seamless use of ADO.NET to read and write XML data. Data Access with ADO.NET CHAPTER 8 j 430234 Ch 08. qxd 7/1/03 9:01 AM Page 289 This chapter starts. the server. The DataReader requires a command and connection (see Figure 8. 1). The Data- Reader returns a forward-only, read-only data stream from a data source. This stream represents the fastest