1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu MASTERING SQL SERVER 2000- P15 docx

50 355 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Thông tin cơ bản

Tiêu đề Security and SQL Server 2000
Trường học University of Technology Sydney
Chuyên ngành Database Security and Programming
Thể loại Giáo trình
Năm xuất bản 2000
Thành phố Sydney
Định dạng
Số trang 50
Dung lượng 549,66 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

associ-The Connection object represents an open connection to an OLE DB data source.You can create a Connection object and use it to create other objects further down theADO object hiera

Trang 1

you have a well-designed security plan that incorporates growth, managing your userbase can be a painless task.

To limit administrative access to SQL Server at the server level, you learned thatyou can add users to a fixed server role For limiting access in a specific database, youcan add users to a database role, and if one of the fixed database roles is not to yourliking, you can create your own You can even go so far as to limit access to specificapplications by creating an application role

Each database in SQL Server 2000 has its own independent permissions Youlooked at the two types of user permissions: statement permissions, which are used tocreate or change the data structure, and object permissions, which manipulate data.Remember that statement permissions cannot be granted to other users

The next section in this chapter described the database hierarchy You looked atthe permissions available to the most powerful user—the sa—down through thelower-level database users

You then learned about chains of ownership These are created when you grantpermissions to others on objects you own Adding more users who create dependentobjects creates broken ownership chains, which can become complex and tricky towork with You learned how to predict the permissions available to users at differentlocations within these ownership chains You also learned that to avoid the brokenownership chains, you can add your users to either the db_owner or the db_ddladmindatabase role and have your users create objects as the DBO

Permissions can be granted to database users as well as database roles When a user

is added to a role, they inherit the permissions of the role, including the Public role,

of which everyone is a member The only exception is when the user has been deniedpermission, because Deny takes precedence over any other right, no matter the level

at which the permission was granted

We then looked at remote and linked servers, and at how security needs to be

set up to make remote queries work We finished with a look at n-tier security and

applications

Now that you have a better understanding of security and administration in eral you are ready to start learning about programming with SQL Server Let’s start inthe next chapter by learning about ADO

Trang 4

CHAPTER 19

ADO and SQL Server

F E A T U R I N G :

Trang 5

In most applications involving SQL Server, not all of the development is done on

the server itself This is the essence of client-server computing: Work is tioned between a central server and distributed clients To view and modifyserver-side data from a client application, one uses a client data-access library.Over the years, Microsoft has released a number of client data-access libraries thatcan use SQL Server data, including DB-Lib, Data Access Objects (DAO), and RemoteData Objects (RDO) Although all of these libraries are still in use, they’re no longerundergoing active development Instead, Microsoft recommends that all new clientapplications use ActiveX Data Objects (ADO) to interact with the server

parti-ADO is the only client data-access library that we’re going to cover in this book.Even if you’ve used another library for that purpose in the past, you should considermigrating to ADO to take advantage of current advances in the state of the art In thischapter, we’ll start by describing the ADO object model and then take a look at whatyou can do with ADO We’ll close with a brief section on ADOX, an ADO extensiondesigned to help you work with schema information

ADO provides an object model atop the OLE DB interface, which is the low-level

“plumbing” that SQL Server uses between its own components Because of this mate connection, ADO is a good choice for working with data stored in SQL Server

inti-The ADO Object Model

Figure 19.1 shows the ADO object model for ADO 2.6, the version that ships with SQL

Server 2000 An object model lists the various objects that a library contains and shows

their relationships As you can see, the ADO object model is fairly simple

Trang 6

In addition to the objects shown in Figure 19.1, the Connection, Command,Parameter, Recordset, Record, and Field objects each have a Properties collection ofProperty objects This enables your code to easily enumerate the properties ofthese objects Objects shown in Figure 19.1 with multiple boxes are collections

For example, the Command object contains a Parameters collection containingindividual Parameter objects

NOTE Despite the simplicity of the ADO object model, ADO offers quite a bit of ity in its operations, because there are many alternatives for performing basic operations, aswell as lots of optional arguments In this chapter, we’ll provide the basics of ADO to get youstarted For more details, refer to the Microsoft Data Access Components SDK You candownload a copy of this SDK, which has the complete documentation for all ADO objects,

complex-from the Microsoft Universal Data Access Web site at http://www microsoft com/data

Understanding Objects

Before we dig into the objects offered by ADO, let’s step back a bit and talk about the

concept of an object in programming In software development, an object represents a

package of functionality provided for client programs to use Usually an object sents some “thing” within a particular piece of software Objects have methods (activ-ities they can perform), properties (characteristics that describe the objects), andevents (occurrences that can cause the object to invoke your code) that are set by theprovider of the object As an application developer, you can use those methods andproperties to interact with the original product

repre-For example, ADO includes an object called a Recordset This object represents aset of records (for example, the results of a query) from a data provider A Recordsetobject can be used to represent any set of records The Recordset object has methods,such as MoveFirst (which positions an internal pointer to the first record in theRecordset) and MoveLast (which positions an internal pointer to the last record in theRecordset) It also has properties, such as RecordCount (the number of records in theRecordset) and EOF (a Boolean property that indicates the last record of the Recordsethas been retrieved) The Recordset object also has events, such as FetchComplete,which occurs when all of the records from an asynchronous operation are available inthe Recordset

Objects can be arranged in collections, which are groups of similar objects For

example, in ADO there is a Parameters collection of Parameter objects You can use a

THE ADO OBJECT MODEL

Development with S QL Server

P A R T

V

Trang 7

collection to view each object in turn of a similar group This is called iterating

through the collection

Objects can also contain other objects For example, the ADO Recordset objectcontains a collection of Field objects, each of which represents one of the individualfields in a record in the Recordset

Objects provide an abstract view of the underlying software It’s unlikely thatthere’s actually a data structure within SQL Server that you could point to and say,

“This is a Recordset.” By manipulating Recordsets in your code, though, you canaccess many of the abilities of SQL Server to retrieve and modify data The Recordsetobject provides a convenient abstraction for the underlying functionality of storingand modifying data

In the remainder of this section, we’ll discuss the objects that the ADO objectmodel provides We’ll keep the discussion on an abstract level, without presenting all

of the methods and properties of each object SQL Server Books Online includes anexhaustive list of these methods and properties, as well as those of the other objectmodels that can be used with SQL Server

Connection and Error

At the top of the ADO hierarchy, you’ll find the Connection object, which is ated with an Errors collection Neither of these objects provides a direct connection todata, but they’re both very important in working with other ADO objects

associ-The Connection object represents an open connection to an OLE DB data source.You can create a Connection object and use it to create other objects further down theADO object hierarchy However, if you need only a single Recordset object from a par-ticular Connection, it’s probably more efficient to just create the Recordset directly,which will create a Connection object implicitly You should reserve explicitly creat-ing actual Connection objects for situations where you’ll need to perform multiple,diverse operations on the connection

An Error object represents a single error Because one data-access operation cangenerate multiple errors, Error objects are contained in an Errors collection If the lastoperation succeeded, this collection will be empty Otherwise, you can use the ForEach operator to examine each Error in turn

Command and Parameter

The Command and Parameter objects are the basic query-building objects of ADO.You can use them in various combinations to represent tables, SQL statements, orstored procedures You can use Command objects both for commands that return

Trang 8

to a valid connection string This will cause ADO to create an implicit Connectionobject for use by this Command only However, if you’re going to execute multipleCommands on a single Connection, you should avoid this technique, because it willcreate a separate Connection object for each Command Instead, you can set theActiveConnection property to an existing Connection object.

A Parameter object represents a single parameter for a Command object Thismight be a runtime parameter in a SQL query, or an input or output parameter in astored procedure If you know the properties of a particular Parameter, you can usethe CreateParameter method to make appropriate Parameter objects for a Commandobject, which allows you to initialize parameters without any server-side processing

Otherwise, you must call the Refresh method on the Command object’s Parameterscollection to retrieve parameter information from the server, a resource-intensiveoperation

Recordset and Field

The Recordset and Field objects are the actual data-containing objects in ADO

A Recordset object represents a set of records retrieved from SQL Server Becausethis is the object that allows you to directly retrieve data, it’s indispensable to ADOprocessing ADO allows you to open a Recordset object directly, or to create one from

a Connection or Command object As you’ll see later in the chapter, Recordsets have

a variety of properties and behaviors depending on how they’re created

A Field object represents a single column of data in a Recordset Once you’veretrieved a Recordset, you’ll usually work with the Fields collection to read the data inthe Recordset However, since the Fields collection is the default property of theRecordset object, you won’t often see its name in your code For example, if you’reworking in Visual Basic or a VBA host application, the following two lines of codeproduce an identical result:

Recordset.Fields(0).ValueRecordset(0)

THE ADO OBJECT MODEL

Development with S QL Server

P A R T

V

Trang 9

special-Record and Stream

For completeness, you should also know about two other objects introduced inADO 2.5, although these objects are not useful in working with SQL Server data.The Record object is a dual-purpose object It can represent a row in a Recordset Itcan also represent a file or folder in a file system However, it’s important to realizethat these are not distinct features of the Record object Rather, the Record object isdesigned to represent a row in a Recordset when the underlying OLE DB provider nat-urally supports a hierarchical data store For example, Record objects can be used withproviders that supply information from file systems or e-mail storage Record objectscan’t be used with providers that supply information from standard relational data-bases (even if there’s a hierarchy within the database)

The Stream object represents binary data associated with a Record object Forexample, if you have a Record object representing a file in a file system, its associatedStream object would represent the binary data in that file

Because SQL Server is a relational database, it doesn’t support Record or Streamobjects

Understanding Cursors

You learned about T-SQL cursors in Chapter 8 A cursor, you’ll recall, is a set of recordsalong with a pointer that identifies one of these records as the current record ADOalso supports cursors, in the form of the Recordset object When you open a Recordsetobject to contain a set of records, ADO identifies a particular record as the currentrecord Thus, if you talk of cursors in an ADO context, you’re normally talking aboutRecordsets

Unlike T-SQL cursors, though, ADO cursors can have a variety of different iors, depending on the properties you set for the Recordset object In this section,we’ll discuss the three key properties that control ADO cursor behavior:

behav-• CursorLocation

• CursorType

• LockType

Trang 10

CursorLocation

The CursorLocation property can be set to either adUseServer, for server-side cursors,

or adUseClient, for client-side cursors A cursor is a set of records in memory, and ofcourse some software has to be responsible for keeping track of this set of records

Server-side cursors are maintained by SQL Server using the same native cursors thatyou met in Chapter 8 Client-side cursors are maintained by the Microsoft Cursor Ser-vice for OLE DB, which attempts to level the playing field by supplying capabilitiesthat are lacking in some servers If no CursorLocation is specified, a server-side cursor

is the default

Just because SQL Server supports server-side cursors doesn’t mean you have touse them Some functionality is available only in client-side cursors—for example,re-sorting Recordsets or using an index to find records If you need these capabili-ties, you should use client-side cursors Otherwise, you may find that server-sidecursors provide better performance

• To open a keyset Recordset, use adOpenKeyset A keyset Recordset functionslike a dynamic Recordset, except that you won’t see new records added orrecords deleted by other users

• To open a static cursor, use adOpenStatic A static Recordset does not show youany changes made by other users while the Recordset is open and is thereforemost useful for reporting or other applications that don’t need to be kept com-pletely up-to-date

• Finally, to open a only cursor, use adOpenForwardOnly A only cursor is identical to a static cursor, except that you can only move for-ward in the Recordset to go to a different record This offers the fastestperformance of any of the cursor types, at the expense of flexibility Some-

forward-times you’ll see a forward-only, read-only cursor called a firehose cursor

UNDERSTANDING CURSORS

Development with S QL Server

P A R T

V

Trang 11

NOTE The forward-only Recordset is more flexible than you might think at first In tion to using the MoveNext method, you can also use the Move method to skip interveningrecords, as long as you’re moving forward A forward-only Recordset also supports theMoveFirst method, although this seems contradictory Be aware, though, that this may be

addi-an expensive operation, because it might force the provider to close addi-and reopen theRecordset

In general, if you stick to a cursor type that has no more functionality than youneed in your application, you’ll get the best possible performance If you don’t specify

a cursor type, ADO defaults to the fastest type, which is a forward-only cursor

LockType

Finally, you can use the LockType parameter to specify the record-locking behaviorthat will be used for editing operations Here again you have four choices:

• adLockReadOnly, for Recordsets that cannot be edited

• adLockPessimistic, for pessimistic locking (record locks are taken for the tion of all editing operations)

dura-• adLockOptimistic, for optimistic locking (record locks are taken only while data

read-WARNING The default Recordset in ADO is server-side, forward-only, and read-only

If you want to move through records at random or edit records, you must specify the cursor type and lock type to use

Graceful Degradation

Just to make things more interesting, what you ask for isn’t always what you get.Not every provider supports every possible combination of these parameters Inalmost every case, though, you’ll get something close to what you asked for The

Trang 12

ADO term for this process is graceful degradation Rather than refuse to create a

Recordset, ADO will always return some kind of Recordset However, for example, ifyou try to open a client-side, static, pessimistic Recordset on a SQL Server datasource, what you actually get will be a client-side, static, batch optimistic Recordset

If you aren’t sure what you’re getting, you need to check the values of the CursorType,CursorLocation, and LockType properties of the Recordset object after calling its Openmethod to see what ADO delivered

TI P You should also realize that different Recordsets can have very different mance implications In general, the Recordsets with fewer capabilities are faster, but you’llwant to test this in your own application to determine the best type of Recordset to open

perfor-Table 19.1 shows the possible options you can choose when opening a Recordsetusing SQL Server data and the actual Recordsets that are delivered by ADO

TABLE 19.1: GRACEFUL DEGRADATION OF RECORDSETS

Server-side, forward-only, read-only Server-side, forward-only, read-only YesServer-side, forward-only, pessimistic Server-side, forward-only, pessimistic YesServer-side, forward-only, optimistic Server-side, forward-only, optimistic Yes

Yes

Server-side, keyset, read-only Server-side, keyset, read-only YesServer-side, keyset, pessimistic Server-side, keyset, pessimistic YesServer-side, keyset, optimistic Server-side, keyset, optimistic YesServer-side, keyset, batch optimistic Server-side, keyset, batch optimistic YesServer-side, dynamic, read-only Server-side, dynamic, read-only YesServer-side, dynamic, pessimistic Server-side, dynamic, pessimistic YesServer-side, dynamic, optimistic Server-side, dynamic, optimistic YesServer-side, dynamic, batch optimistic Server-side, dynamic, batch optimistic YesServer-side, static, read-only Server-side, static, read-only YesServer-side, static, pessimistic Server-side, keyset, pessimistic NoServer-side, static, optimistic Server-side, keyset, optimistic NoServer-side, static, batch optimistic Server-side, keyset, batch optimistic No

Server-side, forward-only, batch optimistic

Server-side, forward-only, batch optimistic

UNDERSTANDING CURSORS

Development with S QL Server

P A R T

V

Trang 13

TABLE 19.1: GRACEFUL DEGRADATION OF RECORDSETS (CONTINUED)

Client-side, forward-only, read-only Client-side, static, read-only NoClient-side, forward-only, pessimistic Client-side, static, batch optimistic NoClient-side, forward-only, optimistic Client-side, static, optimistic No

No

Client-side, keyset, read-only Client-side, static, read-only NoClient-side, keyset, pessimistic Client-side, static, batch optimistic NoClient-side, keyset, optimistic Client-side, static, optimistic NoClient-side, keyset, batch optimistic Client-side, static, batch optimistic NoClient-side, dynamic, read-only Client-side, static, read-only NoClient-side, dynamic, pessimistic Client-side, static, batch optimistic NoClient-side, dynamic, optimistic Client-side, static, optimistic NoClient-side, dynamic, batch optimistic Client-side, static, batch optimistic NoClient-side, static, read-only Client-side, static, read-only YesClient-side, static, pessimistic Client-side, static, batch optimistic NoClient-side, static, optimistic Client-side, static, optimistic YesClient-side, static, batch optimistic Client-side, static, batch optimistic Yes

Sample ADO Code

Understanding the objects supplied by ADO is an important part of grasping thistechnology, but it’s no substitute for actually using those objects In the rest of thischapter, we’ll demonstrate a number of basic ADO techniques for retrieving andworking with data

TI P We can’t hope to cover all of ADO in a single chapter The definitive reference forthis technology is the Microsoft Data Access Components Software Development Kit(MDAC SDK) You can get to the MDAC SDK online by going to the Microsoft UniversalData Access Web site (www.microsoft.com/data) and following the Documentation link

Client-side, static, batch optimistic Client-side, forward-only, batch

optimistic

Trang 14

Creating a Connection

To do anything with ADO, you need to create a Connection object and use it to nect to the database in which you’re interested In some cases, such as when opening

con-a Recordset directly, you won’t need to explicitly crecon-ate the Connection object

There’s always a Connection object involved, even if you don’t explicitly create it

To connect to a database, you use the Connection object’s ConnectionString erty and Open method The ConnectionString property holds an OLE DB connectionstring Connection strings are a standardized method of describing where a database

prop-is and what information should be used when connecting to the database The Openmethod takes some optional arguments:

Connection.Open ConnectionString, UserID, Password, Options

All four of these arguments are optional:

• The ConnectionString argument can be used to supply a connection string whencalling the Open method In this case, you don’t need to set the Connection-String property in advance

• The UserID argument specifies the username to use with the data source

• The Password argument specifies the password to use with the data source

• The Options argument can be set to adConnectUnspecified (the default) for asynchronous connection or adAsyncConnect for an asynchronous connection

Once the connection is made, either type performs the same The difference isthat an asynchronous connection lets other code in your client application con-tinue running while the connection is being made

Of course, to build a connection string, you need to understand from what it’smade up The basic syntax of an OLE DB connection string is as follows:

keyword=value;keyword=value;keyword=value…

Table 19.2 shows the keywords that you can use in a SQL Server connection string

TABLE 19.2: OLE DB CONNECTION STRING KEYWORDS FOR SQL SERVER

Provider SQLOLEDB Must be specified This tells OLE DB the

type of database with which you want toconnect

Data Source Name of the SQL Server Must be specified You can also use the

special value “(local)” if the SQL Server is

on the computer where the client code will run

SAMPLE ADO CODE

Development with S QL Server

P A R T

V

Trang 15

TABLE 19.2: OLE DB CONNECTION STRING KEYWORDS FOR SQL SERVER (CONTINUED)

Server Name of the SQL Server An alternative to the Data Source keyword.Initial Catalog Name of the database Must be specified

Database Name of the database An alternative to the Initial Catalog keyword.User ID Username This applies to SQL Server Authentica-

tion only

Password Password This applies to SQL Server

Authentica-tion only

Trusted_Connection Yes or No Setting to Yes enables Windows NT

Application Name Application name Sets the client application name, which can

be inspected in SQL Server EnterpriseManager

Workstation Workstation name Sets the workstation name, which can be

inspected in SQL Server Enterprise Manager

NOTE In addition to the keywords listed in Table 19.2, there are several more that dealwith network settings In general, you won’t need to worry about these more advancedkeywords

Now that you have all the pieces, it’s just a matter of putting them together Forthe simplest possible case, consider connecting to a server on the same computerwhere you’re running the ADO code, using Windows NT Authentication (this is likely

to be the case if you’re using the MSDE version of SQL Server, for example):

Dim conLocal As ADODB.Connection

Set conLocal = New ADODB.Connection

Trang 16

Dim conLocal As ADODB.Connection

Set conLocal = New ADODB.ConnectionconLocal.Open _

“Provider=SQLOLEDB;Server=(local);” & _

“Database=pubs;Trusted_Connection=Yes”

It really doesn’t matter which of these formats you use to open a connection; youshould choose the one that makes it easier for you to remember what the code isdoing

NOTE We’re using Visual Basic for the examples in this chapter Because ADO is a COMserver, you can use it from any COM-aware language, but we feel that Visual Basic is themost widely understood and the easiest to read even if you don’t know its precise syntax

To use ADO in Visual Basic, you need to use the Project ➢ References menu item to set a

reference to the current version of the Microsoft ActiveX Data Objects Library

Connecting to a SQL Server across the network using a SQL Server user ID andpassword is just as simple For example, to connect with the Northwind database on a

server named BIGREDBARN as a user named test with a password of test, you could

use this code:

Dim conNetwork As ADODB.Connection

Set conNetwork = New ADODB.ConnectionconNetwork.Open _

“Provider=SQLOLEDB;Server=BIGREDBARN;” & _

“Database=Northwind;User ID=test;pwd=test”

Debug.Print conNetwork.ConnectionString

SAMPLE ADO CODE

Development with S QL Server

P A R T

V

Trang 17

Executing a SQL Statement

Once you’ve created and opened a Connection object, you’re ready to work with yourserver One of the easiest tasks to do via ADO is to execute a SQL statement ADO pro-vides two methods for doing this, either of which can be used for executing SQL state-ments or stored procedures:

• The Connection.Execute method

• The Command.Execute method

Using the Connection Object

One way to execute SQL statements is to use the Execute method of the Connectionobject This method takes one required and two optional arguments:

Connection.Execute CommandText, RecordsAffected, Options

The CommandText argument is required This can be either a SQL statement or thename of a stored procedure In this section we’ll use only stored procedures that donot return records; we’ll discuss stored procedures that return records later, when wetalk about the Recordset object

The RecordsAffected argument is a variable (not a constant) If you choose to ply this argument, it will be filled in by SQL Server with the number of records thatthe command altered

sup-The Options argument can either specify how the CommandText should be preted or supply options for executing it Some of the values you can supply forOptions are as follows:

inter-• adCmdUnknown (the default) indicates that ADO should figure out for itselfwhether the command is a SQL statement or a stored procedure

• adCmdText indicates that the command is a SQL statement

• adCmdStoredProc indicates that the command is a stored procedure

• adAsyncExecute tells ADO to execute the command asynchronously

• adExecuteNoRecords indicates that the command does not return any rows Youdon’t have to specify this, but it does make the method more efficient to do so

As a first example, here’s code to execute a SQL statement directly This particularstatement will create a stored procedure in the local copy of the Northwind database:Dim conLocal As ADODB.Connection

Dim lngRows As Long

Set conLocal = New ADODB.Connection

Trang 18

“CREATE PROC NewPrices AS UPDATE Products “ & _

“SET UnitPrice = UnitPrice * 1.1”, lngRows, _adCmdText + adExecuteNoRecords

Debug.Print lngRows

If you run this code, you’ll find that the lngRows variable is set to –1 That’s ADO’sway of telling you that the command didn’t return any rows at all If it had returned

an empty Recordset, lngRows would be set to zero instead

Once you’ve run the above procedure, you now have a stored procedure that youcan execute directly:

Dim conLocal As ADODB.ConnectionDim lngRows As Long

Set conLocal = New ADODB.ConnectionconLocal.Open _

“Provider=SQLOLEDB;Server=(local);” & _

“Database=Northwind;Trusted_Connection=Yes”

conLocal.Execute _

“NewPrices”, lngRows, _adCmdStoredProc+ adExecuteNoRecords

Debug.Print lngRows

On a stock copy of the Northwind database, this code will end up setting lngRows

to 77, the number of rows in the Products table The code will work just as well if youomit the extra information:

Dim conLocal As ADODB.Connection

Set conLocal = New ADODB.ConnectionconLocal.Open _

“Provider=SQLOLEDB;Server=(local);” & _

“Database=Northwind;Trusted_Connection=Yes”

SAMPLE ADO CODE

Development with S QL Server

P A R T

V

Trang 19

Dim conLocal As ADODB.Connection

Set conLocal = New ADODB.ConnectionconLocal.Open _

“Provider=SQLOLEDB;Server=(local);” & _

“Database=Northwind;Trusted_Connection=Yes”

conLocal.NewPricesAssuming that there is a stored procedure named NewPrices in the Northwinddatabase, this bit of code will execute that stored procedure Once again, there’s noreturn value to tell you how many rows were altered

Using the Command Object

The Command object also has an Execute method with three optional arguments:

Command.Execute RecordsAffected, Parameters, Options The RecordsAffected argument is a variable (not a constant) If you choose to supply

this argument, it will be filled in by SQL Server with the number of records that thecommand altered

The Parameters argument can be used to hold a variant array of parameters to be

passed to the command being executed on the server

The Options argument can either specify how the command should be interpreted

or supply options for executing it Some of the values you can supply for Options are

as follows:

• adCmdUnknown (the default) indicates that ADO should figure out for itselfwhether the command is a SQL statement or a stored procedure

• adCmdText indicates that the command is a SQL statement

• adCmdStoredProc indicates that the command is a stored procedure

• adAsyncExecute tells ADO to execute the command asynchronously

• adExecuteNoRecords indicates that the command does not return any rows Youdon’t have to specify this, but it does make the method more efficient to do so

Trang 20

As you can see, this is very close to the Execute method of the Connection object

However, using a separate Command object to execute SQL statements adds someimportant extra capabilities First, you can reexecute the same statement withoutadditional overhead Second, you can use the Command object’s Parameters collec-tion to supply parameters to a SQL Server stored procedure

TIP Although you can use either the Parameters collection or an array of Parameters inthe Execute method to pass parameters, we recommend that you always use the Parameterscollection This is because output parameters do not function properly if passed in an array

To use a Command object to execute a SQL statement, you must create and open aConnection object and then use the Command object’s ActiveConnection property toassociate the Command to the Connection You also need to set the text of the com-mand into the Command object’s CommandText property For example, this codewill execute a SQL statement against the Northwind database on the local server:

Dim conLocal As ADODB.ConnectionDim cmdProc As ADODB.CommandDim lngRows As Long

Set conLocal = New ADODB.ConnectionconLocal.Open _

“Provider=SQLOLEDB;Server=(local);” & _

“Database=Northwind;Trusted_Connection=Yes”

Set cmdProc = New ADODB.CommandSet cmdProc.ActiveConnection = conLocalcmdProc.CommandText = _

“CREATE PROC NewPrices2 AS UPDATE Products “ & _

“SET UnitPrice = UnitPrice/1.1”

cmdProc.Execute lngRows, , _adCmdText + adExecuteNoRecords

SAMPLE ADO CODE

Development with S QL Server

P A R T

V

Trang 21

Dim lngRows As Long

Set conLocal = New ADODB.ConnectionconLocal.Open _

“Provider=SQLOLEDB;Server=(local);” & _

“Database=Northwind;Trusted_Connection=Yes”

Set cmdProc = New ADODB.CommandSet cmdProc.ActiveConnection = conLocalcmdProc.CommandText = “NewPrices2”

cmdProc.Execute lngRows, , _adCmdStoredProc + adExecuteNoRecords

Debug.Print lngRowsYou can also use the Command’s Name property to assign a name to the Com-mand If you do this, you can then treat that command as a method of the corre-sponding Connection object:

Dim conLocal As ADODB.ConnectionDim cmdProc As ADODB.Command

Set conLocal = New ADODB.ConnectionconLocal.Open _

Dim conLocal As ADODB.ConnectionDim cmdProc As ADODB.Command

Trang 22

Dim lngRows As Long

Set conLocal = New ADODB.ConnectionconLocal.Open _

“Provider=SQLOLEDB;Server=(local);” & _

“Database=Northwind;Trusted_Connection=Yes”

Set cmdProc = New ADODB.CommandSet cmdProc.ActiveConnection = conLocalcmdProc.CommandText = “CREATE PROC NewPrices3 “ & _

“@factor float AS UPDATE Products “ & _

“SET UnitPrice = UnitPrice * @factor”

cmdProc.Execute lngRows, , _adCmdText + adExecuteNoRecords

Debug.Print lngRowsThe NewPrices3 stored procedure requires a single parameter named @factor ofdatatype float to do its job To supply this parameter, you can work with the Parame-ters collection of a Command object One way to do this is to use the Refresh method

of the Parameters collection to get parameter information:

Dim conLocal As ADODB.ConnectionDim cmdProc As ADODB.CommandDim lngRows As Long

Set conLocal = New ADODB.ConnectionconLocal.Open _

“Provider=SQLOLEDB;Server=(local);” & _

“Database=Northwind;Trusted_Connection=Yes”

Set cmdProc = New ADODB.CommandSet cmdProc.ActiveConnection = conLocalcmdProc.CommandText = “NewPrices3”

cmdProc.CommandType = adCmdStoredProccmdProc.Parameters.Refresh

cmdProc.Parameters(1) = 1.1cmdProc.Execute lngRows, , _adExecuteNoRecords

Debug.Print lngRows

SAMPLE ADO CODE

Development with S QL Server

P A R T

V

Trang 23

For this technique to work, you need to set the CommandType property of the

Command object to adCmdStoredProc before you call the Parameters.Refresh method.

Otherwise, ADO won’t realize that you’re trying to get stored procedure parameters.The returned parameters are numbered starting at zero, with the zero parameter beingreserved for the stored procedure’s return value So in this case, the only input para-meter is Parameters(1)

Although this technique works, it’s not the best way to do things Calling the meters.Refresh method causes ADO to query SQL Server for parameter information,which takes some time If you know in advance what parameters you need, you cancreate them with the CreateParameter method of the Command object Here’s anexample:

Para-Dim conLocal As ADODB.ConnectionDim cmdProc As ADODB.CommandDim prm As ADODB.ParameterDim lngRows As Long

Set conLocal = New ADODB.ConnectionconLocal.Open _

“Provider=SQLOLEDB;Server=(local);” & _

“Database=Northwind;Trusted_Connection=Yes”

Set cmdProc = New ADODB.CommandSet cmdProc.ActiveConnection = conLocalcmdProc.CommandText = “NewPrices3”

cmdProc.CommandType = adCmdStoredProcSet prm = cmdProc.CreateParameter(“@factor”, adDouble, adParamInput)prm.Value = 1.1

cmdProc.Parameters.Append prmcmdProc.Execute lngRows, , _adExecuteNoRecords

Debug.Print lngRows

To make this technique work, follow these steps:

1 Call the Command.CreateParameter method once for each parameter required

by the stored procedure Supply the name of the parameter, a constant ing the datatype, and another constant indicating whether it’s an input or anoutput parameter

indicat-2 Set the Value property of the new parameter.

3 Append the new parameter to the Parameters collection of the Command

Trang 24

Recordset Operations

Although executing commands is a necessary part of working with SQL Server, moreoften you’ll want to work with groups of records—that is, with Recordset objects Inthis section, we’ll show you the basic Recordset operations:

• Opening a Recordset directly from a table

• Opening a Recordset from an unparameterized query

• Opening a Recordset from a parameterized query

• Moving through a Recordset

• Editing records

• Adding records

• Deleting records

• Persisting Recordsets

Opening from a Table

The first method of the Recordset object you’ll need to use is the Open method Asyou might guess, this is the key method for attaching a Recordset object to a cursor ofrecords:

Recordset.Open Source, ActiveConnection, CursorType,

➥ LockType, Options

All of the arguments to the Open method are optional:

• The Source argument specifies the name of a Command object, a SQL ment, a table name, or a stored procedure name that provides the source for therecords in this Recordset You can set the Recordset’s Source property before call-ing the Open method as an alternative

state-• The ActiveConnection argument associates the Recordset object with the nection object that connects to the SQL Server with which you want to work

Con-You can also set the ActiveConnection property before calling the Openmethod

• The CursorType argument can be set to one of the cursor type constants cussed earlier in this chapter As an alternative, you can set the CursorTypeproperty of the Recordset before calling the Open method

dis-• The LockType argument can be set to one of the lock type constants discussedearlier in this chapter As an alternative, you can set the LockType property ofthe Recordset before calling the Open method

SAMPLE ADO CODE

Development with S QL Server

P A R T

V

Trang 25

• The Options argument can be set to a variety of constants These include:

• adCmdText to specify that the Source argument is a SQL statement

• adCmdTable to specify that the source argument is a table name

• adCmdStoredProc to specify that the source argument is a stored procedure name

• adAsyncExecute to open the Recordset asynchronously

• adAsyncFetch to fill the record cache asynchronously

In addition to the CursorType and LockType properties, the Recordset object alsohas a CursorLocation property that can be set to adUseClient (for client-side cursors)

or adUseServer (for server-side cursors) This property must be set before you call theOpen method; it can’t be supplied as part of the Open method itself

With that explanation out of the way, let’s look at a couple of examples of openingRecordsets based directly on tables Here’s perhaps the simplest possible way to do so:Dim conLocal As ADODB.Connection

Dim rstCustomers As ADODB.Recordset

Set conLocal = New ADODB.ConnectionconLocal.Open _

If you run this code, you’ll notice that rstCustomers.RecordCount reports –1, eventhough there are customers in the database In general, you can’t depend on theRecordCount to accurately count the records in a Recordset Rather, it’s a count of therecords that have been fetched Because this is a forward-only Recordset, there’s noway for ADO to pre-fetch (and therefore count) the records, so it returns the special

value –1 You can think of this value as meaning I don’t know how many records there are here.

Ngày đăng: 21/01/2014, 08:20

TỪ KHÓA LIÊN QUAN

w