Module 3: Performing Connected Database Operations

88 369 0
Module 3: Performing Connected Database Operations

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Module 3: Performing Connected Database Operations Contents Overview Lesson: Working in a Connected Environment Lesson: Building Command Objects Lesson: Executing Command Objects That Return a Single Value 17 Lesson: Executing Commands That Return Rows 24 Lesson: Executing Commands That Do Not Return Rows 35 Lesson: Using Transactions 48 Review 57 Lab 3.1: Performing Connected Database Operations 59 Information in this document, including URL and other Internet Web site references, is subject to change without notice Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, places or events is intended or should be inferred Complying with all applicable copyright laws is the responsibility of the user Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property  2001-2002 Microsoft Corporation All rights reserved Microsoft, MS-DOS, Windows, Windows NT, Win32, Active Directory, ActiveX, BizTalk, IntelliSense, JScript, MSDN, SQL Server, Visual Basic, Visual C#, Visual C++, Visual J#, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A and/or other countries The names of actual companies and products mentioned herein may be the trademarks of their respective owners Module 3: Performing Connected Database Operations iii Instructor Notes Presentation: 120 Minutes Lab: 60 Minutes In many situations, you will design your data access strategy around the use of a DataSet However, you might find it useful or necessary to bypass DataSets and use data commands to communicate directly with the data source After completing this module, students will be able to: ! ! Execute a command that returns a single value ! Execute a command that returns a set of rows, and process the result ! Execute a command that defines database structure and permissions by using the data definition language (DDL) and data control language (DCL) ! Execute a command that modifies data by using the data manipulation language (DML) ! Required materials Build a command object Use transactions To teach this module, you need the following materials: ! ! Module 3, “Performing Connected Database Operations” ! Preparation tasks Microsoft® PowerPoint® file 2389B_03.ppt Lab 3.1, Performing Connected Database Operations To prepare for this module: ! ! Complete the practices and labs ! Hyperlinked code examples Read all of the materials for this module Read the latest NET Development news at http://msdn.microsoft.com/library/default.asp?url=/nhp/ Default.asp?contentid=28000519 This module contains code examples that are linked to text hyperlinks at the bottom of PowerPoint slides These examples enable you to teach from code examples that are too long to display on a slide All of the code examples for this module are contained in one htm file Students can copy the code directly from the browser or from the source, and paste it into a development environment To display a code sample, click a text hyperlink on a slide Each link opens an instance of Microsoft Internet Explorer and displays the code associated with the link At the end of each example is a link that displays a table of contents of all examples in this module After you have finished teaching the code for an example, close the instance of the browser to conserve resources Practices If time constraints occur, one or more practices in this module can be presented as instructor-led demonstrations iv Module 3: Performing Connected Database Operations How to Teach This Module This section contains information that will help you to teach this module Lesson: Working in a Connected Environment This section describes the instructional methods for teaching each topic in this lesson Object Model for Connected Applications Technical Notes: ! Remind students that the Xxx prefix is the notation used on this course, to denote the type of data provider being used Sql represents the SQL Server NET Data Provider, and OleDb represents the OLE DB NET Data Provider ! Tell students that the XxxCommand object encapsulates a SQL statement The XxxCommand object has various “execute” methods, which return different types of results For example, ExecuteReader returns an XxxDataReader object ! The XmlReader object is specific to the SQL Server NET Data Provider Discussion Questions: Personalize the following question to the background of the students in your class • Why are the XxxParameter objects needed? Lesson: Building Command Objects This section describes the instructional methods for teaching each topic in this lesson What Is a Command Object? ! Technical Notes: ! XxxCommand objects will typically map to stored procedures in production-level code You can also use XxxCommand objects to refer to SQL statements and table names, which is convenient for testing ! The ExecuteXmlReader method is only supported by the SQL Server NET Data Provider, because it relies on the ability of SQL Server to return XML data Discussion Questions: Personalize the following question to the background of the students in your class • Ask students what they know about the Connection and Command objects in Microsoft ActiveX® Data Objects (ADO), and describe how the Microsoft ADO.NET versions (XxxConnection and XxxCommand) differ Module 3: Performing Connected Database Operations How to Create a Stored Procedure v Technical Notes: ! The ability to create stored procedures is a useful aid for developers, but it is debatable whether production-level stored procedures will be written by using Server Explorer In all probability, the required stored procedures will already exist on the database, and the database administrator will keep close control over who is allowed to create new stored procedures ! Perform the demonstration in front of the students Discussion Questions: Personalize the following questions to the background of the students in your class ! ! How to Create a Command Object Ask students whether they have ever written a stored procedure, or have seen the syntax before Be prepared to describe stored procedures from first principles, if necessary Server Explorer greatly simplifies the task of developing distributed and enterprise-level applications Stress how useful this tool is, and how much development time it can save Technical Notes: ! If you create a command object programmatically, the default CommandType is Text (which means you must provide a SQL statement) If you want to call a stored procedure, specify CommandType=CommandType.StoredProcedure ! If you create a command object by using the tools, you can create a new connection object at the same time (or use an existing connection object) Discussion Questions: Personalize the following question to the background of the students in your class • Ask students whether they will need to create command objects programmatically for their applications at work, or use the tools to create them automatically Demonstration: Creating a Command Object Graphically Technical Notes: ! This is the easiest way to create a command object It is also the most likely scenario: creating a command object to call an existing stored procedure ! This demonstration relies on the stored procedure you created earlier in this lesson (See the topic How to Create a Stored Procedure in this module.) ! After you have dragged the stored procedure onto the form, note that SqlConnection and SqlCommand objects are generated automatically ! Examine the generated code In particular, describe the initialization of the SqlConnection and SqlCommand objects Discussion Questions: Personalize the following question to the background of the students in your class • How would you generate a command object for a SQL Server 6.5 database? What objects would be generated? vi Module 3: Performing Connected Database Operations What Are Command Parameters? Technical Notes: ! In SQL Server 7, all output parameters are input/output parameters ! You can use parameters in direct SQL statements, as well as in stored procedures Use the syntax @parameterName in the SQL statement, rather than a question mark placeholder Discussion Questions: Personalize the following questions to the background of the students in your class ! ! How to Create Parameters for a Command Object Why use parameters in a SQL statement? What is the difference between an input parameter, an output parameter, and an input/output parameter? Technical Notes: Creating parameter objects programmatically is difficult, especially if you are working with DataSets It is much easier if you can generate the parameters by using the tools in Microsoft Visual Studio NET Discussion Questions: Personalize the following question to the background of the students in your class • Are there any circumstances where you would need to create parameter objects programmatically, rather than by using Visual Studio NET tools? Transition to Practice Exercise: You will now create a stored procedure that uses parameters, and create command and parameter objects to execute the statement Instruct students to turn to the practice exercise at the end of this topic in the student workbook Practice Solution: Create a stored procedure by using a provided SQL script Create a new Windows Application, and drag the stored procedure onto the form Notice that the wizard automatically creates and configures the SqlConnection, SqlCommand, and SqlParameter objects After the Practice: What parameters were created for the stored procedure? How are these parameters initialized? Module 3: Performing Connected Database Operations vii Lesson: Executing Command Objects That Return a Single Value This section describes the instructional methods for teaching each topic in this lesson Why Return a Single Value in a Command? Technical Notes: ! This is the simplest way to execute a SQL statement, but most students will probably be more interested in learning how to execute a query This subject is covered in a later lesson ! Describe the SQL functions on the slide: COUNT, MAX, MIN, and AVERAGE Ask students if they have seen these functions before You can show these functions in SQL Server Books Online if time permits Discussion Questions: Personalize the following questions to the background of the students in your class ! ! How to Execute a Command That Returns a Single Value How many return values can you return from a stored procedure? How can you pass multiple values back from a stored procedure? Technical Notes: ! Note the different syntax in Microsoft Visual Basic® NET and Microsoft Visual C#™ for accessing array elements: the Visual Basic NET syntax is Parameters("@parameterName"), whereas the Visual C# syntax is Parameters["@parameterName"] ! Remind students that the Parameters collection must have been configured before you set its Value property (See the topic How to Create Parameters in this module.) ! Stress the fact that ExecuteScalar returns an Object data type, and describe how and why to cast this into a specific data type Discussion Questions: Personalize the following question to the background of the students in your class • Ask students what value they return from their stored procedures back at work? Specifically, they return a real value or only an error code? Transition to Practice Exercise: You will now create a new Windows Application and execute a SQL statement that returns the count of customers in the Northwind database Instruct students to turn to the practice exercise at the end of this topic in the student workbook Practice Solution: Use ExecuteScalar to execute a SQL statement that returns an integer value After the Practice: • How many customers are in the Northwind database? viii Module 3: Performing Connected Database Operations How to Retrieve Output and Return Values Technical Notes: ! Many SQL developers prefer to use output parameters rather than return values, as a way of passing values back from a stored procedure The return value can then be used to indicate how many rows were affected by the statement, or to convey an error code if there is a problem ! Stress the fact that @RETURN_VALUE is the default name of the returnvalue parameter To use a different name, select the Command object in the Form Designer and view its properties, select the Parameters property to display a dialog box showing the parameters for the command, and change the name of the return parameter if you want to Discussion Questions: Personalize the following question to the background of the students in your class • Ask students to describe the code example for this topic in the student workbook Module 3: Performing Connected Database Operations ix Lesson: Executing Commands That Return Rows This section describes the instructional methods for teaching each topic in this lesson Returning Rows Technical Notes: ! Most students will be comfortable with this concept Emphasize that ExecuteReader returns an XxxDataReader ! Emphasize that XxxDataReader is the most efficient way to process SQL results Discussion Questions: Personalize the following question to the background of the students in your class • What is the equivalent of XxxDataReader in Microsoft ActiveX® Data Objects (ADO)? DataReader Properties and Methods Technical Notes: ! This programming model will be familiar to anyone who has used ADO before, but you should describe the processing for the benefit of students who are unfamiliar with ADO ! The connection is kept open while the XxxDataReader consumes data from the result set Therefore, it is important to close the XxxDataReader as soon as you finish processing the result set ! The correct way to test whether a column contains a null value is to use IsDbNull Discussion Questions: Personalize the following questions to the background of the students in your class ! What data types students have in their databases? ! How many rows students expect to retrieve in a typical query for their applications back at work? ! What metadata students need for their result sets? x Module 3: Performing Connected Database Operations How to Use a DataReader to Process Rows Technical Notes: ! Describe the code sample ! Point out that ListBox has an Items collection in the NET Framework This means you have to write code such as ListBox1.Items.Add( ) to add an item to the ListBox Discussion Questions: Personalize the following question to the background of the students in your class • Describe a scenario where this code sample might be appropriate Transition to Practice Exercise: You will now create a new Windows Application and execute a SQL statement that returns a result set You will display this data in a ListBox control on the form Instruct students to turn to the practice exercise at the end of this topic in the student workbook Practice Solution: Use ExecuteReader to execute the query, and return a SqlDataReader object Use the SqlDataReader object to loop through the result set Append each result to a ListBox control on the form After the Practice: • What is the meaning of CommandBehavior.CloseConnection? Why is this useful? 56 Module 3: Performing Connected Database Operations Define a click event handler for the new button, and add the following code: a Open the database connection b Create and assign a transaction to the command c Set the @ProductName parameter of the command, to the value in the first text box Set the @CategoryID and @SupplierID parameters to d Execute the command e Set the @ProductName parameter to the value of the second text box f Execute the command again g Display a message box asking if the user wants to save the changes If the user selects Yes, commit the transaction Otherwise, roll back the transaction h Close the database connection Run and test the application Type two product names in the text boxes, and then click the button When you are prompted to save changes, click Yes Use Server Explorer to verify that two new records have been added to the Products table Type two different product names in the text boxes, and then click the button When you are prompted to save changes, click No Verify that neither record has been added to the Products table The solution for this practice is available in \Practices\Mod03\Lesson6\ExecutingTransactions\ Module 3: Performing Connected Database Operations 57 Review ! Working in a Connected Environment ! Building Command Objects ! Executing Commands That Return a Single Value ! Executing Commands That Return Rows ! Executing Commands That Do Not Return Rows ! Using Transactions *****************************ILLEGAL FOR NON-TRAINER USE****************************** In what situations would you use the connected environment? What classes would you use for a connected application? A factory that requires a real-time connection to monitor production output and storage A brokerage house that requires a constant connection to stock quotes Class Description XxxConnection Establishes a connection to a specific data source For example, the SqlConnection class connects to Microsoft SQL Server data sources XxxCommand Executes a command from a data source For example, the SqlCommand class can execute stored procedures or SQL statements in a SQL Server data source XxxDataReader Reads a forward-only, read-only stream of data from a data source For example, the SqlDataReader class can read rows from tables in a SQL Server data source It is returned by the ExecuteReader method of the XxxCommand class, typically as a result of a SELECT SQL statement XxxXMLReader Provides fast, non-cached, forward-only access to XML data 58 Module 3: Performing Connected Database Operations For what tasks can you use the command object? Execute SELECT statements that return a single value, such as a row count, the results of a credit-card authentication lookup, or a calculated value Execute SELECT statements that return rows This is an efficient way to load large volumes of read-only data into a control such as a Web Forms DataList or DataGrid Execute DDL statements to create, edit, and remove tables, stored procedures, and other database structures You need the required permissions to perform these actions Execute DCL statements to grant or deny permissions Execute statements to get database catalog information Execute commands that return data from a Microsoft SQL Server database (version 7.0 or later) in XML format A typical use is to execute a query and get back data in XML format, apply an Extensible Stylesheet Language for Transformations (XSLT) transformation to convert the data to Hypertext Markup Language (HTML) format, and then send the results to a browser such as Microsoft Internet Explorer How does the DataReader class work? When you use the DataReader class? The DataReader is a fast, forward-only cursor that loops through a stream of rows When you execute an XxxCommand that returns a set of rows, you use a DataReader to loop through the set of rows What types of statements you use when you not want rows returned? SQL statements such as INSERT, UPDATE, and DELETE that use the ExecuteNonQuery method What is a transaction? A transaction is a set of related tasks that either succeed or fail as a unit In transaction-processing terminology, the transaction either commits or rolls back For a transaction to commit, all participants must guarantee that any change to data will be permanent Changes must persist despite system failures or other unforeseen events Module 3: Performing Connected Database Operations 59 Lab 3.1: Performing Connected Database Operations ! Executing a Command Object That Returns a Single Value ! Executing a Command Object That Returns Records ! Executing a Command Object That Returns Multiple Results ! Executing a Command Object That Modifies the Database *****************************ILLEGAL FOR NON-TRAINER USE****************************** Objectives After completing this lab, you will be able to: ! ! Execute a command object that returns a single value ! Execute a command object that returns records ! Execute a command object that returns multiple results ! Prerequisites Build a command object Execute a command object that modifies the database Before working on this lab, you must have: ! Microsoft Visual Basic® or Visual C# programming skills ! Familiarity with the Visual Studio NET development environment For more information Search online Help for the topic “Databases in Server Explorer.” Hint: Use quotation marks (“ ”) around the topic titles when searching the Visual Studio NET online documentation Scenario Northwind Traders has a corporate local area network (LAN) that provides employees with easy access to the Northwind database Employees need to access the information in this database, to make business decisions about which products to stock and the pricing policy for these products These tasks are performed only by office workers Mobile workers not perform these tasks A connected Windows Application satisfies these requirements Solution Files Before running the solution files you must create the stored procedures they use in Microsoft SQL Server 60 Module 3: Performing Connected Database Operations ! To create the stored procedures Start the Microsoft SQL Server Query Analyzer Switch to the Northwind database Open and run the scripts named CountProducts.sql, GetMultipleResults.sql, GetOrderSummary.sql, and SummarizeOrders.sql in the folder \2389\Labs\Lab03\Starter\ Close the SQL Server Query Analyzer Estimated time to complete this lab: 60 minutes Module 3: Performing Connected Database Operations 61 Exercise Executing a Command Object That Returns a Single Value In this exercise, you will create a new stored procedure in the Northwind database The stored procedure will return the number of products in the database You will then open an existing Windows Application and add a SqlConnection object to connect to the Northwind database You will also add a SqlCommand object to represent the new stored procedure You will execute the stored procedure by using the ExecuteScalar method and display the result in a message box Scenario The Northwind database contains information about all products stocked by Northwind Traders Employees at Northwind Traders need to know how many products are in a specified price range Employees can access the database over the corporate LAN ! Add a stored procedure to get the number of products Start the Visual Studio NET development environment In the Server Explorer, select the Northwind database on your local computer Add a new stored procedure to the Northwind database The required code for this stored procedure is provided in the file CountProducts.sql in the following location: \Labs\Lab03\Starter Copy this code into the stored procedure in the Visual Studio NET code editor Save the stored procedure ! Add data objects to a Windows Application In Visual Studio NET, open one of the following starter solutions: • If you wish to use Visual Basic, open the starter solution provided in \Labs\Lab03\Starter\VB • If you wish to use Visual C#, open the starter solution provided in \Labs\Lab03\Starter\CS Open the form named FormConnectedApp View the Server Explorer, and find the CountProducts stored procedure in the Northwind database Drag this stored procedure onto your form Visual Studio NET creates a SqlConnection object and a SqlCommand object In the Properties window for the SqlConnection object, set the following property Property Value (Name) cnNorthwind 62 Module 3: Performing Connected Database Operations In the Properties window for the SqlCommand object, set the following property Property Value (Name) cmCountProducts Review the code for your application Notice the code that creates the parameters for the command ! Execute the stored procedure Add an event handler method for the Click event on the Count Products button In the event handler method, get the text in the txtMinimumPrice and txtMaximumPrice text boxes Use the double.Parse method to convert these strings to the double data type Assign the double values to two local double variables Use these values to set the @Min and @Max parameters in the cmCountProducts stored procedure command Open a connection to the database Use the ExecuteScalar method to execute the cmCountProducts stored procedure command Convert the return value into an integer, and assign it to a local integer variable Close the database connection Display a message box, to show the return value from the cmCountProducts stored procedure command ! Build and test the Windows Application Build the application, and correct any build errors Run the application Enter values such as 10 and 100 for the minimum and maximum prices Click Count Products, and observe the result displayed in the message box Module 3: Performing Connected Database Operations 63 Exercise Executing a Command Object That Returns Records In this exercise, you will create another stored procedure in the Northwind database The stored procedure will execute a SQL query, to obtain all products in stock within a specified price range You will extend the Windows Application from Exercise 1, to call the stored procedure by using the ExecuteReader method You will loop through the records by using a SqlDataReader, and display the product details in a list box Note: You will extend the stored procedure in Exercise 3, to return the out-ofstock records as well Scenario Employees at Northwind Traders need to obtain information about all products currently in stock, within a specified price range ! Add a stored procedure to return products in stock In the Server Explorer, select the Northwind database on your local computer Add a new stored procedure to the Northwind database The required code for this stored procedure is provided in the file GetProductsInRange.sql in the following location: \Labs\Lab03\Starter Copy this code into the new stored procedure in the Visual Studio NET code editor Save the stored procedure ! Add a SqlCommand object to represent the new stored procedure Open the solution you completed in the previous exercise In the Server Explorer, find the GetProductsInRange stored procedure in the Northwind database Drag this stored procedure onto your form Visual Studio NET creates a new SqlCommand object In the Properties window for the new SqlCommand object, set the following property Property Value (Name) cmGetProductsInRange ! Execute the stored procedure Add an event handler method for the Click event on the Display Products button Clear the contents of the lstInStock list box Using the values in txtMinimumPrice and txtMaximumPrice, set the @Min and @Max parameters in the cmGetProductsInRange stored procedure command Open a connection to the database 64 Module 3: Performing Connected Database Operations Declare a local variable named drProducts, of the type System.Data.SqlClient.SqlDataReader Call the ExecuteReader method on the cmGetProductsInRange command Assign the result to the drProducts variable Use drProducts to loop through the product records For each product record, get the following column values Column Code to get this column value ProductID drProducts.GetInt32(0) ProductName drProducts.GetString(1) UnitPrice drProducts.GetSqlMoney(2).ToDouble() For each product, add an item containing this information to the lstInStock list box Close drProducts Close the database connection ! Build and test the Windows Application Build the application, and correct any build errors Run the application Enter values such as 10 and 100 for the minimum and maximum prices Click Display Products Observe the information displayed in the in-stock list box Note that the outof-stock list box is still empty at this stage Module 3: Performing Connected Database Operations 65 Exercise Executing a Command Object That Returns Multiple Results In this exercise, you will extend the stored procedure from Exercise The stored procedure will now return two results: the products that are in stock, and the products that are out of stock You will also extend the Windows Application from Exercise 2, to process the multiple results You will use the SqlDataReader to display the in-stock products first You will then call the NextResult method in SqlDataReader to advance the data reader to the second result You will loop through this result, to display the out-of-stock products Scenario Employees at Northwind Traders need to know which products are in stock, and which products are out of stock This enables employees to make business decisions based on current stock levels ! Return multiple results from a stored procedure In the Server Explorer, select the Northwind database on your local computer Open the dbo.GetProductsInRange stored procedure in the code editor Modify the stored procedure, so that it returns two results: • The in-stock products (within the specified price range) Note: the SELECT statement to this already exists in the stored procedure • The out-of-stock products (within the specified price range) The complete code for this stored procedure is provided in the file GetMultipleResults.sql in the following location: \Labs\Lab03\Starter Save the stored procedure ! Process multiple results Open the solution you completed in the previous exercise Find the event handler method for the Click event on the Display Products button After the lstInStock list box has been populated with the first result, but before closing drProducts, call the NextResult method on drProducts Clear the contents of the lstOutOfStock list box Use drProducts to loop through the out-of-stock products For each record, get the following column values Column Code to get this column value ProductID drProducts.GetInt32(0) ProductName drProducts.GetString(1) UnitPrice drProducts.GetSqlMoney(2).ToDouble() For each product, add an item containing this information to the lstOutOfStock list box 66 Module 3: Performing Connected Database Operations ! Build and test the Windows Application Build the application, and correct any build errors Run the application Enter values such as 10 and 100 for the minimum and maximum prices Click Display Products Observe which products are in stock, and which products are out of stock Module 3: Performing Connected Database Operations 67 Exercise Executing a Command Object That Modifies the Database In this exercise, you will write a stored procedure to create an OrderSummary table in the Northwind database The stored procedure will populate the table with the total number of orders for each product You will also write a stored procedure to query the data in the OrderSummary table In your Windows Application, you will use the ExecuteNonQuery method to execute the first stored procedure You will use the ExecuteQuery method to execute the second stored procedure, and create a SqlDataReader to loop through the result Scenario The Orders table in the Northwind database contains information for each customer order The details of each order are in the Order Details table The Order Details table indicates the quantity required for each product in the order Employees at Northwind Traders need a summary of the total number of orders for each product This information will help Northwind Traders identify its most popular products, so that the company can offer the best possible service to its customers ! Add a stored procedure to create and fill the OrderSummary table In the Server Explorer, select the Northwind database on your local computer Add a new stored procedure to the Northwind database The required code for this stored procedure is provided in the file SummarizeOrders.sql in the following location: \Labs\Lab03\Starter Copy this code into the new stored procedure in the Visual Studio NET code editor Save the stored procedure ! Add a stored procedure to query the OrderSummary table Add another new stored procedure to the Northwind database The required code for this stored procedure is provided in the file GetOrderSummary.sql in the following location: \Labs\Lab03\Starter Copy this code into the new stored procedure in the Visual Studio NET code editor Save the stored procedure 68 Module 3: Performing Connected Database Operations ! Add SqlCommand objects to represent the new stored procedures Open the solution you completed in the previous exercise In the Server Explorer, find the SummarizeOrders stored procedure in the Northwind database Drag this stored procedure onto your form Visual Studio NET creates a new SqlCommand object In the Properties window for this SqlCommand object, set the following property Property Value (Name) cmSummarizeOrders Drag the GetOrderSummary stored procedure onto your form Visual Studio NET creates another new SqlCommand object In the Properties window for this SqlCommand object, set the following property Property Value (Name) cmGetOrderSummary ! Execute the stored procedures In the Windows Form Designer, click the Product Orders tab on your form Add an event handler method for the click event on the Summarize Orders button In the event handler method, clear the contents of the lstOrderSummary list box Open a connection to the database Call the ExecuteNonQuery method on the cmSummarizeOrders command Declare a local variable named drProducts, of the type System.Data.SqlClient.SqlDataReader Call the ExecuteReader method on the cmGetOrderSummary command Assign the result to the drProducts variable Use drProducts to loop through the records For each record, get the following column values Column Code to get this column value Orders drProducts.GetInt32(0) ProductName drProducts.GetString(1) For each record, add an item containing this information to the lstOrderSummary list box Close drProducts 10 Close the database connection Module 3: Performing Connected Database Operations ! Build and test the Windows Application Build the application, and correct any build errors Run the application Click the Product Orders tab on the form Click Summarize Orders Observe the total number of orders for each product 69 THIS PAGE INTENTIONALLY LEFT BLANK ... module, you need the following materials: ! ! Module 3, ? ?Performing Connected Database Operations? ?? ! Preparation tasks Microsoft® PowerPoint® file 2389B_03.ppt Lab 3.1, Performing Connected Database. .. demonstrations iv Module 3: Performing Connected Database Operations How to Teach This Module This section contains information that will help you to teach this module Lesson: Working in a Connected. .. Describe typical connected data access scenarios ! Describe the ADO.NET classes that are used in those scenarios Module 3: Performing Connected Database Operations Object Model for Connected Applications

Ngày đăng: 18/10/2013, 18:15

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan