Tải bản đầy đủ (.pdf) (88 trang)

Module 3: Performing Connected Database Operations

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.03 MB, 88 trang )







Contents
Overview 1
Lesson: Working in a Connected
Environment 2
Lesson: Building Command Objects 4
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

Module 3: Performing
Connected Database
Operations




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
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:
!
Build a command object.
!
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).
!
Use transactions.

To teach this module, you need the following materials:
!
Microsoft® PowerPoint® file 2389B_03.ppt
!
Module 3, “Performing Connected Database Operations”
!
Lab 3.1, Performing Connected Database Operations

To prepare for this module:
!
Read all of the materials for this module.
!
Complete the practices and labs.

!
Read the latest .NET Development news at

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.
If time constraints occur, one or more practices in this module can be presented
as instructor-led demonstrations.

Presentation:
120 Minutes

Lab:
60 Minutes
Required materials
Preparation tasks
Hyperlinked code
examples
Practices
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.
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.
!
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 7 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.

Object Model for
Connected Applications
What Is a Command
Ob
ject?
Module 3: Performing Connected Database Operations 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.
!
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.


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?

How to Create a Stored
Procedure
How to Create a
Command Ob
ject
Demonstration: Creating
a Command Object
Graphically
vi Module 3: Performing Connected Database Operations



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.
!
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:
1. Create a stored procedure by using a provided SQL script.
2. Create a new Windows Application, and drag the stored procedure onto the
form.
3. 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?
What Are Command
Parameters?
How to Create
Parameters for a
Command Object
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.
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 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, do 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?

Why Return a Single
Value in a Command?
How to Execute a
Command That Returns
a Sin
gle Value
viii Module 3: Performing Connected Database Operations


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 return-
value 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.

How to Retrieve Output
and Return Values
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.
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)?

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 do students have in their databases?
!
How many rows do students expect to retrieve in a typical query for their
applications back at work?
!
What metadata do students need for their result sets?

Returning Rows
DataReader Properties
and Methods
x Module 3: Performing Connected Database Operations


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:
1. Use ExecuteReader to execute the query, and return a SqlDataReader
object.
2. Use the SqlDataReader object to loop through the result set.
3. Append each result to a ListBox control on the form.

After the Practice:
• What is the meaning of CommandBehavior.CloseConnection? Why is this
useful?
How to Use a
DataReader to Process
Rows
Module 3: Performing Connected Database Operations xi



Technical Notes:
!

A stored procedure can contain several SQL statements. A stored procedure
can also return several result sets. This is useful because it encapsulates
several related tasks in the same stored procedure.
!
Explain the stored procedure in the notes page for this topic.
!
Emphasize the NextResult method and the RecordsAffected property in
the XxxCommand object.
!
There is a practice for this topic. Treat this as an optional practice; only
allow students to do this practice if time permits.

Discussion Questions: Personalize the following question to the background of
the students in your class.
• Have you ever encountered stored procedures that return multiple result
sets? Would this capability be useful?

Transition to Practice Exercise: You will now create a new Windows
Application that executes a stored procedure containing two SQL SELECT
statements. You will display each result set in a separate 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:
1. Use ExecuteReader to execute the query, and return a SqlDataReader
object.
2. Use the SqlDataReader object to loop through the result set, and append
each result to a ListBox control on the form.
3. Use NextResult, to move on to the result set of the second SQL query.
4. Use the SqlDataReader object to loop through the second result set, and

append each result to a second ListBox control on the form.

After the Practice:
• How would you modify this code, if the stored procedure sometimes only
returned a single result set?

How to Execute Multiple
SQL Statements
xii Module 3: Performing Connected Database Operations


Lesson: Executing Commands That Do Not Return Rows
This section describes the instructional methods for teaching each topic in this
lesson.
Technical Notes: Many students will be unfamiliar with DDL and DCL, so
explain the code examples carefully. Concentrate on DDL, as it is unlikely that
many students will use DCL frequently.
Discussion Questions: Personalize the following question to the background of
the students in your class.
• Ask students if they will use DDL and DCL in their applications, or will
these tasks be performed by the DBA?

Technical Notes: Describe the code sample.
Discussion Questions: Personalize the following question to the background of
the students in your class.
• Why might you be interested in knowing the number of rows affected by a
DDL statement?

Transition to Practice Exercise: You will now create a new Windows
Application and execute a SQL statement that creates a new table 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 ExecuteNonQuery to execute the DDL statement.
After the Practice:
• Why create tables programmatically, rather than by using a tool such as
Query Analyzer?

Technical Notes:
!
Remind students that DML includes SELECT, UPDATE, INSERT, and
DELETE statements. We have already discussed SELECT in the previous
lesson (by using ExecuteReader). To execute UPDATE, INSERT, and
DELETE statements, you call ExecuteNonQuery.
!
Remind students about the syntax for these statements. Refer students to
Appendix A, Overview of SQL Statements and Stored Procedures, for more
information about SQL syntax.

Discussion Questions: Personalize the following question to the background of
the students in your class.
• Ask students if their applications back at work use DML to update data in
the database, or only query data by using the SELECT statement.

What are DDL and DCL
Statements?
How to Execute DDL and
DCL Statements
What Are DML
Modification

Statements?
Module 3: Performing Connected Database Operations xiii


Technical Notes: Describe the code sample.
Discussion Questions: Personalize the following question to the background of
the students in your class.
• Why might you be interested in knowing the number of rows affected by a
DML modification statement?

Transition to Practice Exercise: You will now create a new Windows
Application and execute a SQL statement that inserts new rows into the
Products table 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 ExecuteNonQuery to execute the INSERT statement.
After the Practice:
!
What is @@IDENTITY? Why might this be useful?

Technical Notes: Stress that these problems are detected at run time, not
compile time.
Discussion Questions: Personalize the following questions to the background
of the students in your class.
!
What happens if these problems arise?
!
If you do not get an exception, does this mean that everything has worked
correctly?


Transition to Practice Exercise: You will now create a new Windows
Application and deliberately cause an exception while updating the database.
Instruct students to turn to the practice exercise at the end of this topic in the
student workbook.
Practice Solution: Use ExecuteNonQuery to delete rows from the Product
database. See what happens if there are child rows dependent on this row.

After the Practice:
• What happens if you try to delete a row that has child dependencies?

How to Execute DML
Modification Statements

Troubleshooting Data
Modification
xiv Module 3: Performing Connected Database Operations


Lesson: Using Transactions
This section describes the instructional methods for teaching each topic in this
lesson.
Technical Notes: Most students know about transactions, so move quickly
here. Do not dwell on the technical descriptions, but emphasize the key points
only.
Discussion Questions: Personalize the following questions to the background
of the students in your class.
!
Ask students about ACID properties.
!

Ask students how they use transactions with their applications back at work.

Technical Notes:
!
This approach does not involve ADO.NET. All of the transactional logic
takes place in a stored procedure.
!
You can mention save points here if you like.

Discussion Questions: Personalize the following questions to the background
of the students in your class.
!
Ask students about the benefits and drawbacks of controlling transactions
within a stored procedure.
!
Ask students if they use this approach back at work, to control transactions.

Technical Notes:
!
The XxxTransaction object is separate from XxxConnection. This helps to
keep the XxxConnection object a lightweight object. (In ADO, transactions
were part of the Connection object.)
!
Discuss the code sample.

Discussion Questions: Personalize the following questions to the background
of the students in your class.
!
Ask students about the benefits and drawbacks of controlling transactions
within ADO.NET.

!
Ask students if they use this approach back at work, to control transactions.

What Is a Transaction?
How to Manage
Transactions Using SQL
Statements
How to Manage
Transactions Using
ADO.NET
Module 3: Performing Connected Database Operations xv


Technical Notes: Support for isolation levels varies greatly from one type of
database to another.
Discussion Questions: Personalize the following question to the background of
the students in your class.
• Ask students which isolation level is most appropriate for the types of
applications that they develop at work.

Transition to Practice Exercise (Optional): You will use transactions to
commit or roll back a series of operations.
Instruct students to turn to the practice exercise at the end of this topic in the
student workbook.
Practice Solution: Use BeginTransaction to start a transaction, followed by
Commit or Rollback as appropriate.

After the Practice:
• Is this an appropriate use of transactions?


What Are Isolation
Levels?
xvi Module 3: Performing Connected Database Operations


Review: Connecting to Data Sources
This section provides the answers to review questions at the end of this module.
1. 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.


Module 3: Performing Connected Database Operations xvii


2. 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.



3. How does the DataReader class work? When do 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.


4. What types of statements do you use when you do not want rows returned?
SQL statements such as INSERT, UPDATE, and DELETE that use the
ExecuteNonQuery method.


5. 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 1


Overview
!
Working in a Connected Environment
!
Building Command Objects

!
Executing Command Objects 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 many situations, you will design your data access strategy around the use of
a DataSet. However, in other situations you might find it useful or necessary to
bypass DataSets and use data commands to communicate directly with the data
source (typically, a database). These situations include:
!
Performing queries on data intended to be read-only in your application.
This might include executing a command that performs a database lookup.
!
Designing data access in a Microsoft
®
ASP.NET Web application that only
requires a single pass through data, such as displaying the results of a
search.
!
Executing a query that returns a single value, such as a calculation or the

result of an aggregate function.
!
Creating and modifying database structures, such as tables and stored
procedures.

When you create tables and stored procedures, or otherwise execute logic that
does not return a result set, you cannot use a DataSet and must use data
commands.
After completing this module, you will be able to:
!
Build a command object.
!
Execute command objects that return 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.
!
Use transactions.

Introduction
Ob
jectives
2 Module 3: Performing Connected Database Operations


Lesson: Working in a Connected Environment

!
Object Model for Connected Applications
"
Typical scenarios for a connected environment
"
.NET Framework classes used in a connected
environment application

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
This lesson explains typical disconnected data access scenarios that will be
examined in more detail during the rest of this course.
After completing this lesson, you will be able to:
!
Describe typical connected data access scenarios.
!
Describe the ADO.NET classes that are used in those scenarios.

Introduction
Lesson ob
jectives
Module 3: Performing Connected Database Operations 3


Object Model for Connected Applications
Data Source
XxxConnection

XxxParameter
XxxDataReader
XxxCommand
XxxParameter
XxxParameter
XmlReader
Classes in a Connected Application

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
You might need to build a connected application whenever your application
must have a direct and continuous connection to the data source. Some
examples of connected applications include:
!
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

The following table describes the core classes that are used in a connected
environment.
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.



Typical scenarios for a
connected application
Classes used in a
connected environment
4 Module 3: Performing Connected Database Operations


Lesson: Building Command Objects
!
What Is a Command Object?
!
How to Create a Stored Procedure
!
How to Create a Command Object
!

Demonstration: Creating a Command Object
Graphically
!
What Are Command Parameters?
!
How to Create Parameters for a Command Object

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Command objects allow you to access data directly in the database in a
connected environment.
You can use a command object to perform the following tasks:
!
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 (version
7.0 or later) database 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 HTML
format, and then send the results to a browser such as Microsoft Internet
Explorer.

After completing this lesson, you will be able to:
!
Create a command object.
!
Configure the properties in a command object.
!
Set parameters in a command object.

Introduction
Lesson ob
jectives
Module 3: Performing Connected Database Operations 5


What Is a Command Object?
!
A command object is a reference to a SQL statement or
stored procedure
!
Properties
"
(Name), Connection, CommandType, CommandText,

Parameters
!
Methods
"
ExecuteScalar, ExecuteReader, ExecuteNonQuery
"
ExecuteXmlReader (SqlCommand only)

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
A command object contains a reference to a SQL statement or stored procedure
that you can execute directly. The two command classes are described in the
following table.
Command class Description

System.Data.SqlClient.SqlCommand SQL Server .NET Data Provider command
System.Data.OleDb.OleDbCommand OLE DB .NET Data Provider command

The properties of a command object contain all of the information necessary to
execute a statement against a database. This information includes:
!
(Name). The programmatic name of the command object. Use this name in
your code, to refer to the command object.
!
Connection. The command object references a connection object, which it
uses to communicate with the database.
!

CommandType. One of: Text, StoredProcedure, TableDirect.
!
CommandText. The command object includes the text of a SQL statement
or the name of a stored procedure to execute.
!
Parameters. The command object may include zero or more parameters.

Introduction
Properties of a
command object
6 Module 3: Performing Connected Database Operations


After configuring the properties for a command object, you call one of the
following methods to execute the command. The method you call depends on
the statement or procedure being executed, and the results that you expect to be
returned.
Method in XxxCommand class Description

ExecuteScalar Executes a command that returns a single value.
ExecuteReader Executes a command that returns a set of rows.
ExecuteNonQuery Executes a command that updates the database or
changes the database structure. This method
returns the number of rows affected.
ExecuteXmlReader
(SqlCommand only)
Executes a command that returns an XML result.
Capability supported by SQL Server version 7.0
or later.



Methods of a command
object
Module 3: Performing Connected Database Operations 7


How to Create a Stored Procedure
!
Server Explorer
"
On the View menu, click Server Explorer, or press
Ctrl+Alt+S
"
Create a data connection
"
Click New Stored Procedure
"
Insert SQL
!
Demonstration
"
Creating a stored procedure
"
Testing a stored procedure

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************

Microsoft Visual Studio
®
.NET includes tools to help you create a stored
procedure.
!
To use the Server Explorer to create a stored procedure
1. On the View menu, click Server Explorer, or press Ctrl+Alt+S.
2. To create a connection to the database in which you wish to create the
stored procedure, right-click the Data Connections folder and then click
Add Connection.
3. Expand the new connection and the Stored Procedures folder.
4. Right-click the Stored Procedures folder and then click New Stored
Procedure.
5. Enter the SQL script. You can right-click anywhere on the script and then
click Insert SQL to use the graphical Query Editor.
6. Close and save the stored procedure.

Introduction
Creating a stored
procedure

×