Вы находитесь на странице: 1из 638

David Sceppa

Microsoft'

ADO.NET

Microsoft Press

Microsoft

ADO.NET

2003

. V I L IfII H
FL U
II 11 (

004.45
32.973.26-018.2
28

.
28

Microsoft ADO.NET/. . .: -
, 2003- 640 .: .
ISBN 5-7502-0223-2
ADO.NET, Microsoft .NET Framework.
ADO.NET , , . ADO.NET * , , .
, , DataAdapter.DataSet,
Connection, Command, Transaction, DataReader . Windows- Web-
ADO.NET
Web
Microsoft Visual Studio .NET ADO.NET, ,
ADO.NET
14 , .
-
.
004.45
32.973-26-018.2
Microsoft Corporation, . , .
Microsoft, Microsoft Press, MSDN, Visual Basic, Visual C*. Visual InterDev, Visual Studio, Windows
Windows NT
Microsoft / . .
, , , , , , .

, Microsoft Corporation, 2002


, Microsoft
Corporation, 2003
BN 0-7356-1423-7 (.)
ISBN 5-7502-0223-2

, - ,
2003

XXI

XXII

XXII
XXII
XXIII

XXIV

MICROSOFT ADO.NET

1 ADO.NET


ADO.NET
.NET


.NET

Connection
Command
DataReader
Transaction
Parameter
DataAdapter

DataTable
DataColumn
Constraint
DataRow
DataSet
DataRelation
Data View

DataSet
,

3
4
6
7
7
7
8
8
8
9
9
9
10
10
10

12
12
1-4
14
15
16
17
18
19
20

2 ADO.NET-
DataForm Wizard

21


Data Form Wizard


DataSet

21
22
24
27
27

VI






DataRelation

Update DataAdapter



Data Form Wizard

,

28
29
30
31
31
32
33
34
35
35
36
38
38

:
.NET

39

40

Connection
Connection


OLE DB SQL Server
OLE DB Oracle
OLE DB Access
OLE DB ODBC

Data Links

Data Links
.udl-




,
,


Connection
Command


Visual Studio .NET,
Connection Server Explorer
Server Explorer
OLE DB, ODBC .NET


41
44
44
4
46
47
47
47
48
49
49
50
50
51
52
53
53
53
54
54
55
56
58
58
60
60
61
62
62

VII



Connection

?
OleDbConnection
OleDbConnection
Connections tring
ConnectionTimeout
Database DataSource
Provider
ServerVersion
State
OteDbConnection
BeginTransaction
ChangeDatabase
Close
CreateCommand
GetOkDbSchemaTable
Open
ReleaseObjectPool
OleDbConnection
InfoMessage
StateChange
,

62
63
63
64
65
66
67
67
67
68
68
68
69
70
70
71
72
72
72
74
75
75
76
78
79

81

Command
Command
,
DataReader




DataReader
,




Command Visual Studio .NET

Connection
Query Builder
Command
Server Explorer
Command DataReader Parameter
OleDbCommand
CommandTimeout

Command
Type
Parameters ..

81
81
82
85
86
86
89
90
92
93
94
96
98
99
100
101
101
102
104
105
106
106
107
107
109

VIII

Transaction
UpdatedRowSource
OleDbCommand
Cancel
ExecuteNonQuery
ExecuteReader
ExecuteScalar
Prepare
ResetCommandTirneoui
OleDbDataReader
Depth GetData
FieldCount
IsClosed
Item
RecordsAffected
OleDbDataReader
Read
GetValue
>
GetValues
NextResult
Close
GetName. GetOrdinal GetDataTypeName
GetSchemaTable
GetData Depth
Parameter
OleDbParameter
ParameterName
Direction
Value
SourceColumn SourceVersion
DbType OleDb Type
Precision, Scale Size
,

109
109
110
110
Ill
Ill
113
113
4
114
114
114
114
114
115
115
115
116
116
116
117
117
118
118
119
119
120
120
121
121
122
122
122
123

5 DataAdapter

133

DataAdapter
DataAdapter ,

DataAdapter

DataAdapter DataSet
DataAdapter
, DataSet
DataAdapter
DataAdapter

TableMappings
DataAdapter
DataAdapter
DataAdapter

134
134
134
135
135
135
137
137
138
139
139
140

IX


141
Fill
141
DataTable DataColumn Fill ... 142
Fill
143

144
Fill
145
DataSet
14
TableMappings DataAdapter
14
MissingMappingAction
148

148

149
Oracle
150

150
MissingSchemaAction
ISO
FillScherna
151
DataAdapter Visual Studio .NET
151
DataAdapter
151
Data Adapter Configuration Wizard
151
Server Explorer
155
,
DataAdapter
157
,
157
DataAdapter
158
DataAdapter
158
SelectCommand, UpdateCommand, InsertCommand
DeleteCommand
159
TableMappings
159
MissingMappingAction MissingSchemaAction
161
AcceptChangesDuringFill
162
ContinueUpdateOnError
162
DataAdapter
163
Fill
163
FillSchema
166
GetFillParameters
17
Update
17
DataAdapter
168
FiltError
168
RowUpdacing RowUpdated
19
,
171

:
DATASET ADO.NET

173

174

DataSet

DataSet

, ,


XML

174
175
175
175
176
176
176

DataSet
DataSet
, DataAdapter.Fill
DataTable
DataColumn
, DataAdapter
DataRow
DataRow
DataRow DataTable
DataSet
DataColumn, ...
Constraints DataTable

DataAdapter.FillSchema
DataTable
DataTable
DataTable Tables DataSet
DataTable
DataColumn



,
DataTable, Customers,
Orders Order Details
DataTable
DataRow

Null DataRow
DataRow
DataRow
DataRow.RowState
DataRow
DataSet Visual Studio .NET
DataSet DataAdapter
DataSet
DataSet
DataSet, DataTable, DataColumn, DataRow, UniqueConstraint
ForeignKeyConstraint
DataSet
CaseSensitive
DataSetName
DesignMode
EnforceConstraints
ExtendedProperties
HasErrors
Locale
Namespace Prefix
Relations
Tables
..

17"
177
177
178
178
179
180
181
181
182
183
184
185
186
186
186
187
188
188
190
192
196
197
200
200
202
204
205
206
206
208
211
211
214
217
221
221
221
222
222
222
222
223
223
224
224
224

XI

DataSet
AcceptChanges RejectChanges
Beginmit Endlnit
Clear
Clone
GetChanges
GetXmJ GetXmlSchema
HasChanges
Merge
ReadXtnl Wri teXml
ReadXmlSchema, WriteXmlSchema InferXrnlSchema
Reset
DataSet
MergeFailed
DataTable
CaseSensitive
ChildReiations ParentRelations
Columns
Constraints
DataSet
DefaultView
DesignMode
ExtendedProperties
HasErrors
Locale
MinimumCapacity
Namespace Prefix
PrimaryKey
Rows
TableName
DataTable
AcceptChanges RejectChanges
Beginlnit Endlnit
BeginLoadData EndLoadData
!
Clear
Clone
Compute
GetChanges
GetErrors
ImportRow, LoadDataRow NewRow
Reset
Select
DataTable
:
ColumnChanged ColumnChanging
RowChanged RowChanging
RowDeleted RowDeJeting
DataColumn
AllowDBNull
Autolncrement, AutoIncrementSeed AutoIncrementStep

224
225
226
226
226
226
227
227
227
227
2.27
227
228
228
228
229
229
229
229
230
230
230
230
230
231
231
231
231
232
232
232
233
233
233
233
234
234
235
235
235
236
236
236
236
237
237
237
238
238

XII

Caption
ColumnMapping
ColumnName
DataType
DefaultValue
Expression
ExtendedProperties
MaxLength
Namespace Prefix
Ordinal
Readonly
Table
Unique
DataRow
HasErrors
Item
ItemArray
RowError
RowState
Table
DataRow
AcccptChanges RejectChanges
BeginEdit, CancelEdit EndEdit
ClearErrors
Delete
GetChildRows
GetColumnError SetColumnError
GetColumnsInErrar
GetParentRow, GetParentRows SetParentRow
HasVersion

238
239
239
239
240
240
241
241
242
242
242
242
242
243
243
243
243
244
244
244
244
245
245
247
247
247
247
248
248
249

IsNull
UniqueConstraint
Columns
ConstraintName
ExtendedProperties
IsPrimaryKey
Table
ForeignKeyConstraint
AcceptRejectRule, DeleteRule UpdateRuie
Columns RelatedColumns
ConstraintName
ExtendedProperties
RelatedTable Table
,

7



Recordset ADO

249
:

250
250
250
251
251
251
251
251
252
252
252
252
252

255
256
256
257
258

XIII

DataReiation ADO.NET
DataReJation
DataReiation

GetChildRows DataRow
GetParentRow DataRow
GetParentRows DataRow

DataReiation


-! !
DataReiation,

DataReiation DataColumn.


DeleteRule UpdateRule ForeignKeyConstraint

DataReiation Visual Studio .NET
DataReiation DataSet

DataReiation DataSet
DataReiation
DataReiation
ChildColumns
ChildKeyConstrain!
ChildTable
DataSet
ExtendedProperties
Nested
ParentColumns
ParentKeyCorestraint
ParentTable
RelationName
,

259
260
260
262
263
263
264
2(55
266
266
267
268
269
2~ 1

289

, ,

274
277
277
278
279
279
280
281
281
281
282
282
282
282
282
284
284
284
284
284

DataTable



-
Select


Data View
Data View DataTable

Data
View

SQL-
Data View

Data
View
RowStateFilter ..
..

289
289
292
293
293
295
295
296
297
297
298
298
299
300

XIV

DataRowView
, DataView
DataView
Find
FindRows
DataRowView
DataView Visual Studio .NET
DataView
DataView
DataView
DataView
AllowDelete, AUowEdit AllowNew
ApplyDefaultSort
Count Item
DataViewManager
RowFilter
RowStateFilter
Sort
Table
DataView
AddNew Delete
Beginlnit Endlnit

Find FindRows
GetEnumerator
ListChanged DataView
DataRowView
DataView^
IsEdit IsNew
Item
Row
RowVersion
DataRowView
BeginEdit, CancelEdit EndEdit
CreateCMdView
Delete
,

300
301
303
303
304
305
306
306
306
307
307
307
308
308
309
309
309
310

310
310
3

312
313
314
315
315
315
315
315
316
316
316
316
317
317

9 DataSet

323

DataSet

WriteXmlSchema DataSet
XML Schema Definition Tool

?
DataSet

324
324
324
325
326
328
329
329
331
.. 332

NULL

DaraSet, DataTable DataRow
DataSet





DataSet


,

10



Recordset ADO

Recordset ADO
Command ADO.NET
DataAdapter ADO.NET
DataAdapter


CommandBuilder
CommandBuilder
CommandBuilder

Data Adapter Configuration Wizard
DataAdapter






WHERE
timestamp

NULL

TableMappings

OleDbCommandBuilder
OleDbCommandBuilder
DataAdapter
.'
QuotePrefix QuoteSuffix
OleDbCommandBuilder

XV

333
334
335
336
336
336
338
340
340
341
342
343
344

346
349
350
350
352
362
362
363
367
373
373
374
374
375
37(5
377
378
379
379
382
382
383
383
383
385
385
386
388
391
394
395
395
395
395
396

XVI

DeriveParameters
GetDeleteCommand, GetlnsertCommand
GetUpdateCommanct
RefreshSchema
,

396
397
397
398

11

404


timestamp

UpdatedDataSource Command

RowUpdated
DataAdapter
Timestamp

SQL Server
@@IDENTITY SCOPEJDENTITY
Access 2000
Oracle
DataColumn

,
NOCOUNT SQLServer

,
Select
DacaTable
GetChanges . . , .



GetChanges
Merge DataSet
Merge RowState
Merge

KOI 1
ContinueUpdateOnError DataAdapter



*
DataSet.Merge
Conflicts



.NET Framework

405
406
406
407
407
408
410
410
411
413
414
414
416
417
418
420
420
421
423
423
425
426
428
431
431
438
438
438
439
441
442
442
443
444
445
446
446
447
447

TransactionOption
ADO.NET-


DistributedTransaction
Component Services
ADO.NET
,

12 XML-
XML
XML-
DataSet XML-
GetXml
WriteXml ReadXml
WriteXmlSchema, ReadXmlSchema InferXmlSchema

ADO.NET. XML-

: ?


XML-
XML- diffgram
DataSet + XmlDocurnent = XmlDataDocument
XmlDataDocument
DataSet XML-
XML-
XML- SQL Server 2000
SELECT...FOR XML
, SELECT...FOR XML SQL Server Query
Analyxer
DataSet
XmlDocurnent
SQL XML .NET Data Provider
XmlDocurnent
SqlXmlCommand
DataSet SqlXmLVdapter


SqlXmlCommand

XPath

XSLT-

, SqlXmlCommand
ADO.NET XML

ADO.NET XML
,

XVII

448
449
449
450
451
452
452
452

454
454
4~>5
455
455
456
458
459
460
460
461
461
461
461
462
463
464
46-1
465
467
467
47
468
469
470
471
472
473
474
475
476
476
478
479
481
482
484
484
484

XVIII


ADO.NET

487

13 Windows-

488



1. DataAdapter DataSet
2.
TextBox
3.
4-
DataSee
5. Add Delete
6.
7. Edit. Update Cancel
8.

DataTable Order Details DataSet

DataGrid,


9-
10.

ComboBox

11. -
:





ADO.NET




-
- DataSet
- DataReader
BLOB- Northwind
-
,
ADO.NET
,

14

488
490
491
493
494
496
498
499
501
502
502
503
504
505
508
508
509
512
513
513
513
513
514
514
515
517
517
518
519
519
519
520
522
523
524
524

Web-

Web-
ASP.NRT Web-

528
:

528
528

XIX

. . . . 529
,
529

530

530

531
Access
532
Web-
532
DataBinder.Eval
533
TextBox DataSet
5 34
TextBox DataReader
535
DataGrid
535
DataGrid DataSet
536
DataGrid DataReader
5 36

537

538

538

538

538
cookie
538

539
ViewState
540
Web-
541
Session
541
Application
542
Cache
542

543

543

544

544

54 :>
ViewState
545
Application
545
Session
545

545

545

546
,
Web- DataGrid
546
AllowPaging
547
AllowCustomPaging VirtualltemCount
547
,
DataAdapter
549
,
550
PagingOptions
551
Web-
551

DataGrid
551
, DataGrid , . . 553

554
DataSet
554
UPDATE
555
ShoppingCart
555
,
555

XX

559
.NET

SQL Client .NET Data Provider



SQL Server SqlConnection
SqlDataAdapter
SqlCommand SqlDataReader
GetSqKTMnaHHbix> SqlTypes


ODBC .NET Data Provider
OdbcConnection

OdbcDataAdapter
OdbcDataReader


Oracle Client .NET Data Provider
OracleConnection

OracleDataAdapter
OracleDataReader
Oracle

REF

, .NET
,
.NET


ADO.NET Ad Hoc Query Tool

.NET




ADO.NET DataAdapter Builder

ADO.NET Navigation Control
ADO.NET Navigation Control
Visual Studio .NET
ADO.NET Navigation Control,

ADO.NET Navigation Control

560
560
5
51
562
5
564
566
567
568
569
569
570
570
571
573
573
573
574
574
575
576
577
578
580
580
580
584

587
587
588
588
589
589
592
592
592
593
595
595
595
596"

597
607

. , , , .
(Jackie Richards),
, ADO.NET.
(Sam Carpenter),
, , (Brad Rhodes), .
(Steve DuMosch),
, ,
-.
(Steve Ellis),
, (Dr. Jonathan and Stephanie
Braman), , - .
Microsoft WebData Visual Studio .NET,
.
Microsoft Press,
, .

Microsoft ADO.NET
Microsoft. , , *, , ADO,
Microsoft Visual Studio 6 Data Environment MSDataShape OLE DB Provider.
ADO.NET ,
Microsoft.
: , .
, . , , - , ADO.NET, :
, DataAdapter DataSefi* , DafaSet, , DataSet,
Visual Studio .NET, ?*.


ADO.NET,
, . , DataReader DataSet. ADO.NET ,
, .


, ,
/,
. ,
, Visual Studio .NET.

, , ,
. . , , . . * - .
. ADO.NET Data Form Wizard.

XXIII

,
.NET Connection, Command, DataReader DataAdapter.
* ADO.NET DataSet, DataTable,
DataColumn, DataRotv, DataRelation DataView. ,
DataAdapter, ADO.NET XML-.
Windows- Web -
ADO.NET.

,

OLE DB .NET Data Provider.
.NET, Microsoft .NET Framework, . Microsoft Desktop Engine (MSDE)
Microsoft SQL Server, ,
OLE DB. , SQL Client .NET Data Provider, ODBC .NET Data Provider Oracle
Client .NET Data Provider.
, -: Ad Hoc Query ( ),
DataAdapter Builder (, - DataAdapter^ DataSet, Windows-.
.NET, SQL Client .NET Data Provider ODBC
.NETData Provider. -, , . , ; - . , .
, ,
http://ivunv.ininety.cont, ,
.
- , , . http://ivww.microsoft.com/mspress/books/5354-asp.
, Companion
Content , .
, .


,
-, :

XXIV

Microsoft .NET Framework SDK


( bttp://msdn.microsoft.com/ne);
Visual Studio .NET (, );
Microsoft Internet Explorer 5.01 .


, -. Microsoft Press http://mspress.microsoft.com/support.
Microsoft http://www.microsoft.com/mspress/support/search.asp.
, , ,
Microsoft Press .
:
Microsoft Press
Microsoft ADOMET (Core Reference) Editor
One Microsoft Way
Redmond, WA 98052-6399
:
MSPINPUT@MICROSOET.COM

, .
ADO.NET, Visual Basic .NET, Visual C* .NET, Visual Studio .NET
.NET Framework Web- Microsoft Press Support http://support.microsoft.com.


MICROSOFT ADO.NET

1
ADO.NET

/\DO.NET , Microsoft .NET Framework


.NET. ADO.NET , . ,
ADO.NET , , .
, DataSet, , , , . , DataSet ,

XML. XML- .
, ADO.NET
Microsoft Visual Studio .NET , . , . ,
, . , , , Visual Studio .NET, .
ADO.NET, Visual Studio
.NET, .

1 ADO.NET


, Microsoft, ActiveX Data Objects (ADO), ; ADO
? Microsoft ?
, Visual Basic
. Visual Basic 3-0 Data Access Objects (DAO).
Visual Basic 4.0 - Remote Data Objects (RDO). Visual Basic 5 Visual Studio 97 OBDCDirect. Visual Basic 6 Visual Studio 6 ADO.

.
Microsoft
.
DAO .
Microsoft SQL Server Oracle. DAO ,

. Visual Basic
RDO , . , RDO ,
DAO. Microsoft
ODBCDirect, RDO DAO.
, , , )--
.
ADO.
ADO , ,
. ,
XML-. ADO , . , ADO . , Microsoft ADO
XML-, ADO XML , ADO.NET. ,
ADO.NET , a ADO XML. ADO Recordset , .
ADO ,
. , ADO, ,
.
,
Recordset ADO.
Microsoft ADO.NET ,
, .

1 Microsoft ADO.NET
, ADO
. (common language runtime) .NET Framework Microsoft Visual Studio. Windows Forms Web Forms, . , Microsoft .NET Framework ADO.NET.
ADO.NET , : XML, , .

ADO.NET
ADO.NET Visual
Studio .NET, .
ADO.NET
Microsoft.
ADO.NET
, . . 1-1 ,
ADO.NET. .
(connected). , , . (disconnected), .

OataAdapter
-

. 1-1.

ADO.NET

ADO.NET


. .NET
Framework , , Microsoft . . 1-2 ,NET Framework,

. 1-2. ,NET Framework


. ,
, ,
, . ,
. , . . ,NET Framework
, . ,
. , ,
Microsoft .NET Framework Visual Studio .NET AfSDN.
, ADO.NET. .
Microsoft. ADO
Recordset . Open, , Update ( UpdateBatcfo}
Recordset .
DataSet ADO.NET ( )
Recordset ADO. DataSet .
DataSet Fill ADO.NET DataAdapter. -

I Microsoft ADO.NET

DataSet DataSet DataAdapter-.Update.

.NET
.NET , . .NET Framework
SQL Client .NET Data Provider OLE DB .NET Data Provider. OLE DB .NET Data Provider OLE DB. SQL Client .NET
Data Provider SQL Server 7 .
.NET Connection, Command, DataProvider, Parameter Transaction,
. , SQL Client .NET Data Provider
SqlConnection, OLE DB .NET Data Provider QleDbConnection.
, Connection .
, Connection , ConnectionString nection.Open.
.NET .
.NET Framework SystemData,
. OLE DB .NET Data Provider
SystemData.QleDb, SQL Client .NET Data
Provider SystemDataSqlCUent.
.NET , . , , OLE DB .NET Data Provider SQL Client .NET Data
Provider, , , ,
Visual Basic .NET
'
' OLE DB .NET Data Provider
Dim cnQleOb As New OleDbConnection
cnOleDb.ConnectionString = "Provider=SQLOLEDB;
"Data Source=(local);InitialCatalog=Northwind;..."
cndleDb.OpenO
cnOleDb.CloseQ
'
' SQL Client .NET Data Provider
Dim cnSql As New SqlConnection
cnSql.ConnectiorStrinQ = "Data Source=(local);" &
"Initial Catalog=Northwind;..."

1 ADO.NET
cnSql.OpenO
cnSql.Close()

Visual C#
//
// OLE .NET Data Provider
OleDbConnection cnOleDb = new OleDbConnectionO;
enOleDb.ConnectionString = "Provider=Provider=SQLOLEDB;
"Data Source=(local);InitialCatalog=Northwlnd;...";
enOleDb.OpenO;

cnOleDb.Closef);
//
// SQL Client .NET Data Provider
SqlConnection cnSql = new SqlConnectionC);
cnSql,ConnectionString = "Data Source=(local);" +
"Initial Catalog=Northwind;...";
cnSql.Open();
cnSql.Closet);


Microsoft . ,
Microsoft .
: , .

.NET ? ADO-, , , ADO . ADO, , ADO . ADO.
.NET . , .
SQL Server ADO.NET SQL Client .NET
Provider , ADO OLE DB- SQL
Server, ADO.NET .


SQL Server 2000 XML-,
ADO . ADO
, XML- SQL Server, OLE DB API SQL Server OLE DB Provider.

I Microsoft ADO.NET
.NET .
,
. Command (SqlCommancf) SQL Client .NET Data Provider
, OLE DB
.NET Data Provider,
XML-,

Microsoft Data Access Components (MDAC) 2.0, 1998 ., OLE DB- SQL Server, Microsoft Access
Oracle. Microsoft OLE DB-no ,
. ADO
OLE DB- Microsoft, ,
ODBC- (, OLE DB), - , . OLE DB- .
OLE DB- ODBC- .NET . . Microsoft ADO.NET, .NET. .NET,
ADO.NET.

.NET
.NET ,
.NET , OLE DB .NET Data
Provider. , .NET Framework,
,
, OLE DB-. OLE
DB .NET Data Provider ,

.
.NET .
12 XML- ADO.NET,
SQL Client .NET Data Provider SQL XML .NET Data Provider.
, , , , DataAdapter, OleDbDataAdapter SqlDataAdapter.


ADO.NET , . , . 1-1

1 ADO.NET

, .
,
, .
Connection
Connection .
,
. Connection )-' Connection ADO
Database DAO, .
Connection , ,
DataAdapter Command,
.

Command
Command Command KDO QueryDef
. , .
. ,
. ,
, , . Command .
Command . Connection ,
, CommandText . SQL-, :
SELECT CustomerlD, CompanyName, ContactName,

Phone FROM Customers

,
CommandType .
Command . , ExecuteNonQuery. ExecuteReader
DataReader, . SqlCommand , ExecuteXmlReader, ExecuteReader, , XML

DataReader
DataReader . . . DataReader
, .
DataReader ,
.
2-5958

10

Microsoft ADO.NET

Transaction
. (transaction), , . ,
,
. .
Connection BeginTransaction, Transaction. Transaction
, . , , .

Parameter
, Orders .
:
SELECT CustomerlD, CompanyName, CompanyName, Phone FROM Customers
WHERE CustomerlD = 'ALFKI'

CustomerlD WHERE , .
,
.
, CustomerlD :
SELECT CustomerlD, CompanyName, CompanyName, Phone FROM Customers
WHERE CustomerlD = ?

, , . ,
.
Command
Parameter, ,
Parameters Command. Parameter ADQ.NE1
, . ,
, Direction Parameter
ParameterDirection.

DataAdapter
DataAdapter
Microsoft; ADO , Command
ADO QueryDefDAO .
DataAdapter ADO.NET. DataAdapter Fill

1 ADO.NET

11

DataSet DataTable
. , DataAdapter DataSet .
DataAdapter ADO.NET ,
Command. , SelectCommand
Command, DataSet.
, DataAdapter InsertCommand, UpdateCommand DeleteCommand.
Command , .
Command , Recordset ADO . ,
ADO Recordset, ADO , . ADO , Recordset ,
DataAdapter ADO.NET
UpdateCommand, InsertCommand DeleteCommand"!
. ADO
, Recordset , .
,
. DataAdapter ADO.NET, ADO DAO
.
UpdateCommand, InsertCommand DeleteCommand DataAdapter , ,
.
DataAdapter.Update, ADO.NET Command
DataSet ,
, DataAdapter DataSet,
. DataAdapter
, .
TableMappings ,
DataSet.
ColumnMappings.


, .NET , .

, . ,
, ,
?

12

I Microsoft ADO.NET

ADO.NET , . . DataTable ( ), .
, ,
(disconnected objects).
ADO.NET.
DataTable
DataTable ADO.NET Recordset ADO DAO. .
DataTable, DataAdapterFill:

Visual Basic .NET


Dim strSQL As String = "SELECT CustomerlD, CompanyName FROM Customers"
Dim strConn As String = "Provider=SQLQLEDB;Data Source=(local);..."
Dim daCustomers As New 01eDbDataAdapter(strSQL, strConn)
Dim tblCustomers As New DataTableO
daCustomers,Fill(tblCustomers)

Visual C#
string strSQL = "SELECT CustomerlD, CompanyName FROM Customers";
string strConn = "Provider=SQLOLEDB;Data Source=(local);..."
OleDbDataAdapter daCustomers = new QleDbDataAdapterCstrSQL, strConn);
DataTable tblCustomers = new DataTableO;
daCustomers.Fill(tblCustomers);
, DataTable, . DataTable , ADO.NET . , : , , .
DataTable ,
. DataTable
Roivs, DataRow.
DataTable, Columns
DataColumn. DataTable , . Constraints DataTable.
DataColumn
DataTable Columns, DataColumn. , DataColumn . DataColumn , DataTable, .
(metadata). -

1 ADO.NET

13

, DataColumn ,
(, string integer) . DataColumn ,
Readonly, AHowDBNutt, Unique, Default Autolncrement,
, .
DataColumn Expression, . ,
. , Northwind,
Microsoft, Order
Details UnitPrice Quantity.
, . SQL- ItemTotal.
SELECT OrderlD, ProductlD, Quantity, UnitPrice,
Quantity * UnitPrice AS ItemTotal
FROM [Order Details]

, . DataTable UnitPrice
Quantity, ItemTotal .
ADO.NET Expression, . DataColumn, ADO.NET . , , . ,
Expression:
Visual Basic .NET
Dim col As New DataColumnO
With col
.ColumnName = "ItemTotal"

.DataType = GetType(Decimal)
.Expression = "UnitPrice * Quantity"
End With

Visual C#
QataColumn col = new DataColumnO;

col,ColumnName = "ItemTotal";
col.DataType = typeof(Decimal);
col.Expression = "UnitPrice * Quantity";
Columns DataColumn
Fields Field ADO DAO.

14

I Microsoft ADO.NET

Constraint
DataTable
DataTable . , Constraint,
,
DataTable. Constraint Constraints
DataTable.
Dataflow
, DataTable,
Rows, DataRow. , DataRow . DataRow .
, Item DataRow ,
DataColumn. Item
DataRow , :
Visual Basic .NET
Dim row As DataRow
row = MyTable.Rows(O)
Console.WriteLine(row(O))
Console.WriteLine(row("CustomerlD"})
Console.WriteLineC row(MyTable.Columns("Customs rID")))
Visual C#
DataRow row;
row = MyTable.Rows[0];
Console.WriteLineCrow[0]);
Console.WriteLine(row["CustomerlD"]);
Console.WriteLineCrow[MyTable.Columns["CustomerlD"]]);
, DataTable Rows . Recordset ADO DAO,
MoveNext.
Recordset ADO:
Visual Basic
Dim strConn As String, strSQL As String
Dim rs As ADODB.Recordset
strConn = "Provider=SQLOLEDB;Data Source=(local);..."
strSOL = "SELECT CustomerlD, CompanyName FROM Customers"
Set rs = New ADODB.Recordset
rs.CursorLocation = adUseClient
rs.Open strSQL, strConn, adOpenStatic, adLockReadOnly, adCmdText
Do While Not rs.EOF

1 ADO.NET

15

MsgBox rs("CustomerID")
rs.MoveNext
Loop

DataTable ADO.NET
DataRow Rows-.

Visual Basic .NET


Dim strSOL, strConn As String
Dim da As New 01eDbDataAdapter(str$QL, strConn}
Dim tbl As New DataTableO

da.Fill(tbl)
Dim row As DataRow
For Each row In tbl.Rows
Console.WriteLine(row(0})
Next row
Visual C#
string strSQL, strConn;
OleDbDataAdapter da = new OleDbDataAdapterfstrSQL, strConn);
DataTable tbl = new DataTableO;
da.Fill(tbl);
foreach (DataRow row in tbl.Rows)
Console.WriteLine(row[0]);

DataRow . ,
DataRowBeginEdit, Item EndEdit,
. CancelEdit DataRow ,
. , DataRow Rows,
, DataRoiv ,
. , DataRow ,
. Item DataRow .
DataSet
, DataSet . DataSet DataTable ( Tables
DataSet). : ADO.NET .
.
, DataSet

16

I Microsoft ADO.NET

. DataSet , DataTable.
DataSet .
DataRow.
, ,
DataSet, GetChanges DataSet
. ,
.
DataSet Merge, GetCbanges. , , , Merge DataSet,
DataSet . Merge DataSet . , , ADO.NET
. Microsoft
.
DataSet Tables .
. ADO.NET , .
, DataSet
. DataSet, , . ADO.NET XML-. ADO.NET XML , DataSet ADO.NET
XML- . XML
. , XSLT-, XML- HTML-.

DataRelation
. ,
Northwind Orders Customers, , . ,
, .
DataRelation, DataSet,
DataSet Relations,
DataRelation. DataRelation
DataTable DataSet. DataRelation,
DataRow
, :

Visual Basic .NET


Dim dsNorthwind As DataSet
Dim rowCustomer, rowOrder As DataRow

1 ADO.NET

17

', DataSet
dsNorthwind.Relations.Add("CustomersOrders",
dsNorthwind.Tables("Customers"). ColumnsC "CustomerlD"),
dsNorthwind.Tables( "Orders"), ColumnsC''CustomerlD"))
For Each rowCustomer In dsNorthwind.Tablesf"Customers").Rows
Console.WriteLineC'Orders for customer " 4 rowCustomer("CompanyName"))
For Each rowOrder In rowCustomer.GetChildRows("CustomersOrders")
Console.WriteLine(vbTab 4 rowOrder("OrderID"})
Next rowOrder
Next rowCustomer

Visual C#
DataSet dsNorthwind;
// DataSet
dsNorthwind,Relations.Add("CustomersQrders",
dsNorthwind. Tables["Customers"].Coluinns["CustomerlD"],
dsNorthwind. t)les["Orders"].ColtJmns["CustomerID"]);
foreach (DataRow rowCustomer in dsNorthwind.Tables["Customers"].Rows)
{
Console.WriteLine("Orders for customer " +
rowCustomer["CompanyName"].ToString());
foreach (DataRow rowOrder in rowCustomer.GetChildRows("CustomersOrders"))
Console.WriteLine('\f + rowOrder["OrderID"].ToString());
}

, DataRelation , . , DataRelation
, . DataRelation, ,
,
DataTable
DataTable,

DataView
DataTable, DataView . DataTable , Sort DataView. , Filter DataView
, .
DataTable
DataView. ,
: , , , -

I Microsoft ADO.NET
era . DataView, DataTable.
, . 8.

ADO Recordset , . Fields,


Recordset, , ..
ADO.NET .
ADO.NET ,
.
, ?
- . ?
, ?
, , . , ADO- :
Dim rs as Recordset
'
'
rs.Open strSQL, cnDatabase, adOpenStatic, adLockdptiroistic, adCmdText
Do While Not rs.EOF
Listl.Addltem rs.Fields("UserName").Value
rs.MoveNext
Loop

, UserName,
, , , , . ADO , . ,
OLE DB- ?, ?, ? ?.
,
.
DataSet ADO.NET
. ADO.NET . ,
ADO.NET .
DataSet
, .

1 ADO.NET

19

. Visual Studio .NET , .


, DataSet ,
, ADO.NET-, .
.

DataSet
Visual Studio .NET , DataSet . ,
Orders CustomerlD CompanyName. ,
, .
Visual Basic .NET
Dim ds As DataSet
' DataSet
Console. WriteUne(ds.Tables("Customers").Rows(0)( "CustofnerlD"))

Visual C#
DataSet ds;
// DataSet
Console. WriteLine(ds.Tables["Customers"].Rows[0]["CustomerlD"]);

:
Visual Basic .NET
Dim ds As CustomersDataSet
' DataSet
Console,WriteLine(ds.Customers(0).CustomerlD)

Visual C#
CustomersDataSet ds;
// DataSet
Console. Writel_ine(ds.Customers[0]. CustomerlD);

DataSet ,
Visual Studio .NET . , DataSet .
,
. , :
Visual Basic .NET
Dim ds as DataSet
', DataSet
' DataTable Customers
Dim rowNewCustoroer As Dataflow
rowNewCustomer = ds.Tables("Customers").NewRow()

20

Microsoft ADO.NET

rowNewCustomer("CiistomerID") = "ALFKI"
rowNewCustomer("CompanyName") = "Alfreds Futterkiste"
ds,Tables("Customers").Rows.Add(rowNewCustomer}

Visual C#
DataSet ds;
//, DataSet
// DataTable Customers
Dataflow rowNewCustomer;
rowNewCustome = ds.Tablest"Custome rs"].NewRow();
rowNewCustomer["CustomerID"] = "ALFKI";
rowNewCustomerfCompanyName"] = "Alfreds Futterkiste";
ds.Tables["Customers"].Rows.Add(rowNewCustomer);


:
ds.Customers,AddCustomersRow("ALFKI",

"Alfreds Futterkiste")

DataSet 9-

,
, ADO.NET ADO. ADO.NET
, , , ADO. . ADO.NET.
,
, ADO.NET,
.

" ?

. ADO.NET . , .
ADO.NET . DataSet DataTable
Recordset ADO. DataReader Recordset ADO, , .
. DataTable ADO.NET?
MoveFirst, MoveNext
.. ?
. DataTable Rows, ; , DataTable .
,
MoveFirst, MoveLast, MoveNext MovePrevious .
ADO .

ADO.NET-

DataForm Wizard

:
. , , Microsoft ADO.NET,


, , ,
, Microsoft Visual Basic, , , ,
. .
Data Form Wizard Visual Studio .NET ,
, . ,
, . - .
, , .

I Microsoft ADO.NET

. , * , , ,
, *. , Data Form Wizard Visual Studio .NET , .
,
Northwind, , Microsoft SQL
Server, Microsoft Access Microsoft Data Engine (MSDE).
, Northwind ,
Customers, Orders, Products Employees. ,
, Northwind.


Data Form Wizard
Visual Studio .NET ,
, . Visual Basic .NET *
. Visual Studio Data Form Wizard.
, , ..
.
-, File Visual Studio .NET New\Project
Project . New
Project. Project Types Visual
Basic Visual * Windows Application (. 2-1).
, Chapter2,
.

Project Types:

| vsuarf Basic Projects


&1 Visual C# Projects
jj Setup and Deployment Protects
j.'l Other Project!
[_J Ve-wl 5tudio Solutions

Class Library

Windows
ControlLibrary

Application

ASP MET Vjeb ASP .MET Web eb Control


Application
Service
Library
.A project for creating an application with a Windows user interface
8:

j Chapters]

Location;

j D:\Documents and 5ettings\C)ayidScl.My Documents^, -j

Project win be created at 0:\.. .\113\ Doajmerits\ViijiJ Studio Projacts^Chapt2,


*More

. 2-1.

OK

Cancel

Windows-

2 ADO.NET- DataForm Wizard

23

Web- , 14- Windows-.


Data Form Wizard. -'
, Add New Item. , File
Visual Studio .NET New Add New Item . Data Form Wizard (. 2-2) .
AddNew Item - Chapter?
Templates:

Windows Form

Class

Component
Class

User Control

DataSet

XML Fie

Open

XML Schema

Caned

. 2-2. Data Form Wizard Add New Item


(. 2-3).

. 2-3. Data Form Wizard

I Microsoft ADO.NET

24

Next. DataSet . DataSet


, (. 2-4),
Choose thE dataset vU want to use
The dataset contains [he tflbles and columns to wQ'k with in

. 2-4.

DataSet

DataSet . DataSet
Customers Orders Northwind,
CustomersAndOrders. Next.
Data Form Wizard DataSet .
DataSet , . . ,
.


Data Form Wizard . Choose A
Data Connection (. 2-5) , Server Explorer, .
, New Connection. OLE DB Data Link
Properties.
Connection OLE DB Data Link Properties . Microsoft SQL Server.
, [ (local) SQL Server], ,
(. 2-6).
SQL Server, , ,
^1\11,

2 ADO.NET- DataForm Wizard

25

Wizard
a data connection

Which tdfine hon ihcm Id the fvteard

. 2-5-

. 2-6.

Choose A Data Connection

Connection OLE DB Data Link Properties

SQL Server . , . , SQL Server .


. ,
.
: . 2-7 Allow Saving Password.
. , , , Visual Studio
.NET }' , .
. -

I Microsoft ADO.NET

26

,
. .
3.
, SQL Server, Provider
OLE DB.
OLE DB. Data Link Properties .

osoT SAM 1 1 OLE OB Piovida


EBDttJelDS' CLE DE PfOYidfr
osofUet 4 0 OLE OB Provider
cionCLEUEPrc.:; aCT- Fa.
osoft OLE F-svdtr foi lnde<mg
osol' OLE DB Provri^i lor Interns
oft 59 Piovifei lor Miaosoft !
osofl OLE DE Piovidoi for ODBC
;; \ OLE DB Prouder lor OLAF SF v
[ OLE P'OYioer ft Clj Servit
" u C O L F L F:n,.dei for Oracle

. 2-7.

Provider OLE DB Data Link Properties

SQL Server MSDE, Access- Northwmd, Microsoft Jet 4.0 OLE DB.
Next, Connection (. 2-8).

. 2-8. Access Connection


OLE DB Data Link Properties
Access (...)
,

2 ADO.NET- DataForm Wizard

. . .


Choose Tables Or Views Dara Form Wizard (. 2-9)
, . ,
DataTable ADO.NET. , , .
Available Items
Selected Items, . - Selected Items,
. ,
, .
Ltioose tables or views

Wftal Hirm iui itcaaj <fo fiiu *. ta i

EmployeeTeirilof
Ordai Detalk

. 2-9- Data Form Wizard


Customers Orders Northwind Next.
DataSet
, ,
. 1, . , , ,
DataSet Data Form Wizard
, -,
. ( ).
, Customers Orders. CustomersOrders.

28

I Microsoft ADO.NET

. Orders
Customers. , . , Customers.
Customers Orders
. CustomerlD ; (. 2-10).
, Relations, Next.
Create a relationship between table
The zard wiH ute hhe relationshtps 'o gerie'ate code tbac keeps he

. 2-10.

^^^


Choose Tables And Columns To Display On The Form Data
Form Wizard (. 2-11) ,
. DataSet,
Data Form Wizard
.
master/detail.
, . ; ,
, .
Choose Tables And Columns To Display On The Form Customer , Orders . ,
. Customers Orders,
. Customers Orders, .
, CustomerlD, CompanyName,
ContactTitle Phone Customers CustomerlD, EmployeelD OrderDate Orders. Next.

ADO.NET- DataForm Wizard

29

linfa [nrni Wizard


Choose tables and column: to display on the form
Your fan can display any offhe tables ana cofcurrs e^adaure in

you olspdav more Chan ^ table on the form, [he tetdes ha*E a f attBi

What latikt and cokimn do you font la Unptat anlhtlarm'

. ContaclTI*
'. Address

OrdHOate
II,, .1

. 2-. ,


,
Windows-. ,
,
,
, , .
.
, ,
. , ,
Single Record In Individual Controls ,
. 2-12.
Choose ihe display style
VOLT can drsplay a fjivjle record a', a flte or dsaar all records .

* do ivant taduplay >4rifat4?


'" emrd!E a ett
i* S"ff record f rpdvKkwT confrcdj
What nddKkmel taitralt da yau ant an the farm'
* *|-****01*|1*****,
If you select mdMdual conBolt. you ; s controls fW edUS "nil n*3at(on:
S *1-!8([>!0.
-v fjeiefe - Dria (he curent record.
V Cancel- -?1& chang to ^hecurreriT'et^u.
*" risiatm tonlrolj - Mos loAVsl, BSVBUS, nejl. or .

. 2-12.

30

Microsoft ADO.NET

Web- DataGrid,
HTML-
.
. Finish,



. 2-13 , Data Form
Wizard.

-.ipre,:

Ddtahurml.xbLLkr^ignl |

^fCiisWrper5flndOr6eis
^1
esehiblylnfo.vl:
US DotSomlL,*
S FO.nl vb

jCaUforml Er*en'.V1nifc:

I
AccsiSibleRulf

i OleDbConneaionl

% CfeDbPataAdapte I

. 2-13.

. 2-14.

Chapter2

ADO.NET- DataForm Wizard

31

, . , ,
. , Project Visual Studio .NET
Properties Solution Explorer Properties. Property Pages.
Startup object DataForm 1 (. 2-14). , ,


,
F5; Debug Start Start
, ,
Customers, Orders. .
. DataSet ,
Data Form Wizard, .
Load ,
(. 2-15).

. 2-15.


, Load,
Visual Studio .NET. Load,
, Click LoadDataSet.
, , FtilDataSet, Fill
OieDhDataAdapter (. 2-16).

I Microsoft ADO.NET

32

j"-*F"0tfi

;i)ataforml

pubi

sufc FiUI>aiiiSet(BYVai da^aSet Chapters.cuat

1
tdti
ThrOT
FlnnllJ

He . oiei:o
End Tcy
End 3ub

Cionl. Closed

. 2-16.

ots

chs

-INS

, DataSet

Fill QleDbDataAdapter , SelectCommand DataAdapter,


DataSet DataTable. Data Form Wizard
DataAdapter . SelectCommand
DataAdapter :
SELECT Fieldl. Field2,

FieldN FROM HyTable

,
Add , Delete . .


Dafafle/at/on
, .
.
- DataRelation ( ) ->
, . ,
.
', . Northwind,
(CustomerlD} ALFKI .
CustomerlD Chap2. He :
.
. : CustomerlD Chap2. DataRelation DataSet CustomerlD

2 ADO.NET- DataForm Wizard

33

. , DataSet
.


, DataSet . , .
. , CustomerlD ALFKI. 1, DataSet
. ADO.NET ,
? DataActatper ADO.NET. .
. , .
X. , ,
, .
, - DataSet.
, .
, Update. , , , . ,
. Load, .
roaili t'ltiin.isfc . jdesign] Oet*fomi1.vb

'!, DatffanM.vb I

. 2-17. UpdateDataSet,
Data Form Wizard
Update ?
, Visual Studio .NET.

34

Microsoft ADO.NET

Update Click.
UpdateDataSet LJpdateDataSource. Click Update UpdateDataSet, UpdateDataSource.
. 2-17 2-18.
,
. ,
. 10 11
. :
. ,
. GetChanges, Update Merge,

. 2-18.
UpdateDataSource,
Data Form Wizard

Update DataAdapter
,
Update ,
1, DataAdapter DataSet
, Update DataAdapter DataSet
. DataAdapter DataTable
DataSet. DataTable, Update DataAdapter.
Update DataAdapter , DataAdapter , Update
. , Data

2 ADO.NET- DalaForm Wizard

35

Form Wizard, DataSet, Update DataTable DataRow,


DataAdapter , . , DataAdapter,
Data Form Wizard Customers,
DataTable. DataAdatper , TableMappings, 1.
, DataAdapter ,
, .
, DataAdapter Command,
UpdateCommand. DataAdapter InsertCommand
DeleteCommand .


UpdateRowSource GetCbanges DataSet,
DataSet objDataSetChanges, . GetCbanges
, , , .
Data Form Wizard
GetCbanges DataSet, . DataSet, Update
DataAdapter : , .
GetCbanges?
Data Form Wizard .
. , Web- + , , . ,
.
DataSel
, . . , GetCbanges ADO.NET-.
Data Form Wizard , .


.
DataSet .
,
Update.

36

I Microsoft ADO.NET

GetCbanges DataSet.
DataSet, GetCbanges, Update
DataAclapter.
DataSet objDataSetChanges .
objDataSetChanges DataSet .
- , DataAdapter objDataSetChanges, DataSet.
DataSet Merge,
DataSet. DataSet , ADO.NET
, Merge .
objDataSetChanges ,
DataSet. ,
DataSet objDataSetChanges. ADO.NET , , ,
. ADO.NET DataSet, Merge , , , DataAdapter dsDelta DataSet,
DataSet, .


,
Visual Studio .NET. , Visual
Studio, , , . , Visual Basic 6.
?*
. 2-19 . Visual Studio .NET
. . .
, Visual Basic 6
* *, ,
Properties, - . Visual Basic 6 -,
,
.
Visual Studio .NET , . Properties,
.
, DataConnection, DataAdapter
DataSet.
Data
. , DataAdapter,
.

2 ADO.NET- DataForm Wizard

37

OleDbDataAdapter, DataAdapler,
. ,
, Data Form Wizard. .
, Windows Form Designer generated code
(. 2-20). . , InitializeComponent, , DataAdapter Configuration
Wizard. .

. 2-19. Visual Studio .NET

OMWo.ml.rt I

Gill

Oil

. 2-20. ,

38

Microsoft ADO.NET

Data Form Wizard



!
.
, ,
. ,
. : .
! .
Data Form Wizard , , , .
ADO.NET, .
DataSet,
, Data Form Wizard
. ,
.
Visual Studio .NET , , ,
.
, ,
.

,
, ADO.NET, .
ADO.NET , Data
Form Wizard. , . ,
, , ,
, .
, Data Form Wizard,
.
. , Data Form Wizard, , . OrderlD
. DataSet ?
. , , , , ?
. Update, . DELETE COLUMN REFERENCE. ? ?

.NET

\_/
.
ADO.NET Connection,
Connection ADO.NET.
, Connection Visual Studio .NET.
OleDbConnection
Microsoft .NET Framework Connection .
,
Connection, .NET,

SystemData, SystemData.OleDb SystemDataSqlClient,
( Visual Basic .NET Visual * .NET )
. .
, Visual Basic .NET :
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlCHent

Visual * .NET :
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

41

Connection
Connection ,
. . , Connection
Command
Transaction. ,
Connection.
SQL Server !
(software development kit.
SDK) Microsoft .NET Framework Microsoft "
Desktop Engine 2000 (MSDE).
Access, MSDE , ,
Access Jet, MSDE -
, SQL Server. MSDE , , SQL
Server. , SQL Server, MSDE
. MSDE ,
SQL Server, , , MSDE,
SQL Server.
MSDE SQL Server , . MSDE * SQL
Server. , MSDE
. . SQL Server . MSDE , SQL Server ,
MSDE , SQL Server, Enterprise
Manager, Query Analyzer SQL Profiler.
SQL Server MSDE Web- MSDN SQLServer.
MSDE 2000 Windows 9x
(Windows .98 ), Windows NT
4.0/2000 .

MSDE, .NET Framework SDK.
,
.
MSDE Start,
Microsoft .NET Framework SDK Samples And QuickStart Tutorials,
SDK's QuickStarts, Tutorials, And Samples.
MSDE, , . 3-1. . .
3-5958

II : .NET

Microsoft .NET Framework SDK Quicks tarts, Tutorials and Samples

Nate: The .NET Framework Samples Database seUp program msy requn
return ha this page ID complete the Quickstert tutorials installation.
Step 2: EUJILUlB-3u!kSta!S
Because the QuititStar-s demonstrate a wide

, 3-1. MSDE Microsoft.NET Framework SDK


Install The .NET Framework Samples Database, MSDE, Set Up The QuickStarts
( pubs Northwind SQL Server, , .NET Framework), Internet Information Services (IIS)
Web- QuickStart Tutorial.
MSDE ,NET Framework, SQL DMO.
. SQL DMO -,
, -, Add References.
, . SQL DMO (SQLDMO.chm).

Visual Basic .NET


Dim dffloServer As New SQLBKO.SQLServerO
daioServer.toginSecure * True
dfflOServer.Conneat("(local)\etSDK")
Dim filScrlScript As IQ.StreamReader
Dim strPathToFile As String
Console.WriteLlneC'InstaHing the sample Northwind database")
strPathToFile 'G:\VS.NET\FrameworkSDK\SafHples\Setup\iFistnwnd.sql"
lO.File.DpenText(strPathtoPiie)

43

dmoServer. ExecutelmfnedlateCfllSqlSerlpt. ReadTofnd)


filSqlScript.CloseO
Console.WriteLineC"Instailing the sample pubs database")
strPathToFiie = "C:\VS. NeAFrameworkSDX\Saffiples\Setup\instpu&s.sql"
filSqlScript IQ.File.OpenText(strPathToFile)
dmoServer. Executelmmediate(filSqlSeript.ReatfToEnd)
filSqlScript.CloseO
Din dmoDatabase As SQLDMO.Database
Dim dmoTable As SQLDMO.Table
Console.WriteLineC"Databases:"}
For Each dmoDatabase In dmoServer,Databases
If Not draoDatabase.SystemObject Then
Console.WriteLineCvbTab & draoDatabase.Name)
For Each dmoTable In dmoDatabase.Tables
If Not dmoTable.SystemObject Then
Console.WriteLinefvbTab & vbtab & *noTable,Nae}
Eftd If
Next dmoTable
Console.WriteLineC)
End If
Next efmoDatabase
Dim draoLogin As SQLDMO.Login
Console.WriteLineC"Logins:")
For Each dmoLogin In dmoServer.Logins
Console.WriteLineC vbTab & dstoLogin.Hame)
Next dmoLogin
Console.WriteLineC)
dmoServer.DisConnect{)

Visual C# .NET
SQLDMO,SQLServer dioServer = new SQLDHO.SQLServeK);

dmoServer.LoginSecure = true;
dmoServer.Connect("Clocal)\\NetSDK", null, null);
System.10.Streamfieader filSqlScript;
string strPathToFile;

Console. WriteLinef "Installing the saieple Norttiwlnd database");


StrPathToFile - "C:\\VS,HET\\FrameworkSDK\\Samples\\Setup\\itistnwnd.sql'
filSqlScript = System,10.File.OpenText{StrPathToFile);
dfltoServer, Executelmmediateff ilSqlScrlpt. FteadToEndO,
SOLOMO.SQLDMOLEXEC_TVPE.SQLDMOExec_Default,
null);
filSqlScript.CloseO;

. , ,

44

II : .NET

Console, WriteLine( "Installing the sample pubs database");


strPathToFile = "CiXXVS.NrrXXFramew
filSqlScrlpt = System. 10. File. GpenText(strPathTaFile);
dmaSe rve . Executelmiaediate ( f USqlSc rl pt . ReadToEnd ( ) ,
SQLDMO.SQLDMQ_EXEC,TYPE.SQLDMOExec_Q6fault,
null);
filSsilScript.eiQseO;

Console. WrlteLineC "databases:");


foreach (SQLDHO. Database dmoDatabase in drac-Server. Databases)
if (IdmoDatabase.SystemObject)
I
Console. WrlteLine("\t" + dmoDatabase.Name);
foreach (SQLDHO. Table dmoTable in dmoDatabase. Tables)
If CldnioTable.SystemObject)
Console, WriteLine("\t\t" +
insole, Writeline( ) ;

Console. WriteLine( "Logins: " };


foreach (SQLDHO. Login dmoLogln in dmoServer, Logins)
Cor*sole.WriteLine("\t" + dmologin. );
Console. WriteLineO;
duoServe r, DisCoRfvect( ) ;

Connection
OleDbConnection .
OleDbConnection, :

Visual Basic .NET


Dim en As OleDbConnection
en = New 01eDbConnection()

Visual C# .NET
OleDbConnection en;
en = new OleDbConnectionO;

OleDbConnection
.

Microsoft .NET Framework ,


COM (Component Object
Model) . , . -

45

, . ,
OleDbConnection ,
ConnectionString OleDbConnection.
. , OleDbConnection , OleDbConnection , .
Visual Basic .NET
Dim strConn As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK; " i
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As OleDbConnection
en = New OleDbConnection()
en.ConnectionString = strConn
-

Dim strConn As String


strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" A
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As OleDbConnection
en = New OleDbConnection(strConn)

Visual C# .NET
string strConn;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en;
en = new OleDbConnectionO;
on.ConnectionString = strConn;


string strConn;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en;
en = new OleDbConnection(strConn);
Visual Basic .NET * . , , :

Visual Basic .NET


Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)

46

II

: .NET

Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);


OleDbConnection
, *, :
strConn = "1=31;2=32;..."


.
OLE DB .NET .

OLE DB: Access, SQL Server Oracle.
OLE DB SQL Server
SQL Server OLE
DB, SQL Server, ,
:
Provider=SQLOLEDB;Data 5=; Initial Catalog=BA;
User =;5=;

SQL Sewer 2000,


SQL Server. , Data Source-.
Provider=SQLOLEDB;Data =\;
Initial Catalog=Efl; User =; Password=napont.;

SQL Server ,
Integrated Security :
Provider=SQLOLEDB;Data 8=;Initial Catalog=Bfl;
Integrated Security=SSPI;

. SQL
Server (ODBC) , Trusted_Connection. OLE DB SQL
Server Integrated Security.
, Yes , SSPI-.
Provider=SQLOLEDB; Data 5=;
Initial Catalog=Bfl;Trusted_Connection=Yes;

47

Microsoft Data
Access SDK.
OLE OB Oracle
, ADO.NET Oracle,
ADO.NET . Microsoft
OLE DB Provider for Oracle, Microsoft ODBC Driver for Oracle Oracle, Oracle.
Oracle ADO.NET, Oracle (SQL'Net)
. :
Provider=MSDAORA;Data 5=;
User 10=; Password=napont>;

Microsoft Data
Access SDK.
OLE DB Access
Access
OLE DB Microsoft Jet 4.0 OLE DB Provider. , , :
Provider=Microsoft.Jet.OLEDB.4.0;Data

8=;\\\.;

, ADO
. . ,
Data , :
Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=Data\MyDatabase.MDB;

Jet OLE DB. Microsoft Data Access SDK.


. Access Jet:
Provider=Microsoft.Jet.OLEDB,4.0;
Data Source=C:\.. .;
Jet OLEDB:System database=C:\.. .;
User 10=;Password=flap(Hifa;

, :
Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\...;
Jet OLEDB;Database Password=napcyib;

OLE DB ODBC
ADO, , , OLE DB ODBC, Kagera. -

48

II : .NET

Microsoft Data Access Components 2 . Kagera OLE


DB . ODBC, !
OLE DB API ODBC. ODBC ADO.
Kagera OLE DB .NET , , -, . Microsoft ODBC .NET ( ).
ODBC ODBC .NET. Kagera OLE DB .NET, ,

Data Links
, Visual Studio .NET, Visual
Studio 6, Data Links.
OLE DB ,
, . Data Form Wizard 2.
Data Links Visual Studio .NET,
Data Link. Project
Explorer Add Reference.
Add Reference Microsoft ActiveX
Data Objects 2.7 Library ( ADO) Microsoft OLE DB Service
Component 1.0 Type Library (. 3-2).
-. , Visual Studio .NET
, Yes.
MSDN.
Data Links
, :
Visual Basic .NET
Dim objDataLink As New HSDASC.DataLinksO
Dim en As New ADODB.ConnectionO
objDataLink.PromptEdit(cn)

Console.WriteLineCen.ConnectionString)

Visual C# .NET
MSDASC.DataLlnks objDataLink = new MSDASC.DataLinksClassO;
ADODB.Connection en = new ADODB.ConnectionClass{);
object objCn = (object) en;
objDataLink.PromptEdit(ref objCn);
Console.WriteLine{cn.ConnectionString);

49

Add Reference
.N1

(projects)

I Microsoft Office Web Conponents Wizards


IMicrosoft OLAP Designer Server Driver
Microsoft OLAP Designer Server Driver 8.0
Microsoft OLE DB ActiveX Data Objects I...
Microsoft OLE D6 provider for OLAP Servi...
I Microsoft OLE DB provider for OLAP Ser/i,..
; Microsoft OLEjJBPrJvider for OLftP sjervi...

2.1
1,0
1.0
1,0
1.0
1,0
1,0

'Microsoft OLE DE Simple Provider l.BLibr,., 1 5


J Microsoft Outlook 9,0 Object Library
9.0
! Microsoft PttureCliD Control 6.0 (5P3)
1.1
j WirrncnFf PniunrPriirir Ohi^rt I ihrsrv
?.f>

E:^0fFice2K\0fries\MSO.,
D^ogram Fiies\Commo,
D:\Prcgram FilesKornmo.
D:\Program Fies\Cornmo.
D;\Prcgram File;\Commo,
C^Program Fites|commo.
D;\Ptograoi Fj!es\Comrrra,

E:\Oflice2K\Office|M5O.
D:iw[WNT\System3?\PI,
F:IOffir4?k-lnfFirplM^PP

Microsoft ActiveX DaLa Objects 2.7 Library


Microsoft OLE DB'Sen/ice Component l.DTyjleLbrmY COM

. 3-2. Add Reference


, , ,
Data Links: . , ,
(Peter Gammons) Red Sox Web ESPN.

Data Links
, , Data Links.
.udl. Data Links.

. UDL- ,
Notepad.
! .
.udl-
1
, .udl-. ( , ) .udl-.
.udl-
, :
File Name=MyDataLink.udl;

50

II

: .NET

.udl- , OLE DB .NET


. :
File Name=SettingsSubOir\HyOataL.ink.ucll;


QleDbConnection , . , Open OleDbConnection:

Visual Basic .NET


Dim strConn As String = "Provider=SQLOLEDB; Data Source=(local)\NetSDK;" & _
"Initial Catalog=Nortriwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.OpenO

Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;

, Close-

Visual Basic .NET


Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New 01eDbConnection{strConn)
cn.OpenO

cn.Close()
Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Tru3ted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
on.OpenO;
cn.Close();
, Connection .


.
.

51


. , . 3-3.

\
\
\

Connection

Connection

4-

Connection

<*

. 3-3-
, -,
. - .
-, ,
Connection. , .
- .
, . ,
? . , - .
.
. 3-4.
, ADO.NET .
, . .NET
ADO.NET . ,
.NET ( ,
..) . , .
.
Connection, .NET . , . ( 60 ) , .NET
.

52

II : .NET

. 3-4. ,


.
Connection.
, Close
. .
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalag=Northwind;Trijsted_Connection=Yes;"
Dim en As New 01eDbConnection{strConn)
Dim intCounter As Integer
For intCounter = 1 To 5
cn.0pen()
cn.CloseO
Next
Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;TrustedJ3onnection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
for (int intCounter = 1; intCounter <= 5; intCounter--}
I

cn.OpenO;

53

en.Closet);

,
. ,
For Open, ,
.
Close Connection For , . :
System.Threading.Thread.Sleep(0)

,
, . , , , , .
?
OleDbConnection ReleaseConnectionPool,
Collect ,
, .
. OLE DB :
OLE DB Services=-4;

OLE DB .NET ,
. Close OleDbConnection, -
.
SqlConnection, 1 , .NET,
:
Pooling=False;

,

SQL Server,
.
SQL Profiler Performance Monitor.
Enterprise Manager .


ADO.NET, Connection, Dispose. , . Dispose ,
,
CLR (Common Language Runtime).

54

II : .NET

,
' Connection null Nothing, .
Connection . Dispose
, Close Connection.
, Dispose,
.

Connection
Connection Commands Transaction, .

Command
Command
( 4). ,
Connection Command Connection. Connection
CreateCotnmand, ,
Command,
Connection.
:
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB; Data Source=(local}\NetSDK;" &
"Initial Catalog=Nortnwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.OpenO
Dim cmd As New OleDbCommandO
cmd.Connection = en

Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &


"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.OpenO
Dim cmd As OleDbCominand = cn.CreateCommandO

Visual C# .NET
string strConn = "Provider=SQLOLEDB;Oata Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
en. OpenQ;
OleDbCommand cmd = new OleDbCommandO;
cmd.Connection = en;


string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";

55

OleObConnection en = new 01eDbConnection{strConn);


cn.OpenO;
OleDbCommand end = cn.CreateCommandO;

, Command , Visual Basic .NET CreateCommand.


With
Command, :
Visual Basic .NET
With cn.CreateCommandO
.ConvnandText = "CREATE TABLE MyTable ..."
. ExecuteNonQueryO
.Dispose()
End With
*
. , * With Dispose OleDbCommand, Visual Basic .NET
. Dispose OleDbCommand.
Visual C# .NET
using (OleDbCommand cmd = cn.CreateCommandO {
cmd.CommandText = "CREATE TABLE MyTable . . . " ;

cmd. ExecuteNonQueryO;
}

.
- , .
, . .
Visual Studio .NET , OLE DB, SQL ODBC .NET. Connection OleDbConnection SqlConnection (
, ), , Command,
. .

Connection . BeginTransaciion
Connection
Transaction ( 10).
:
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connectton=Yes;"
Dim en As New OleDbConnection(strConn)
cn.OpenO

56

II : .NET

Dim txn As New 01eDbTransaction()


txn.Connection = en
txn.BeginO

Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\Net$DK;" 4 _


"Initial Catalog=Northwind;TriJsted_Connection=Ye5; "
Dim en As New OleDbConnection(strConn)
cn.0pen()
Dim txn As OleDbTransaction = en.Begin!ransaction()
Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.0pen();
OleDbTransaction txn = new OleDbTransactionQ;
txn.Connection = en;
txn.BeginO;


string strConn = "Provider=SQLOLEDB; Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.0pen();
OleDbTransaction txn = cn.BeginTransaction();


GetOleDbSchemaTable OleDbConnection . (, ), OleDbScbemaGuid.
GetOleDbSchemaTable Restrictions,
. ,
, , . Restrictions . .
. Restrictions;
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
en.Open()
Dim tbl As DataTable
tbl = en.Get01eDbScnemaTable(01eDbSchemaGuid.Tables, Nothing)

57

Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK; " +
"Initial Catalog=Northwlnd;Trusted_Connection=Yes; ";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;
DataTable tbl;
tbl = en. GetOleDbSchemaTableCOleDbSchemaGuid. Tables, null);

, Restrictions . MSDN , Restrictions Table OleDbSchemaGuid :


"^, ".", "_"}
, Customers:
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB; Data Source=(local)\NetSDK" i _
"Initial Catalog=Northwind;Trusted_Connection=Yes; "
Dim en As New OleDbConnection(strConn)
cn.QpenO
Dim objRestrictions As Objectf)
obj Rest fictions = New Object() {Nothing, Nothing, "-Customers", Nothing}
Dim tbl As DataTable
tbl = en. Get01eDbSchemaTable(01eDbSchemaGuid. Columns, objRestrictions)
Visual C# .NET
string strConn = "Provider=SQLOLEDB; Data Source=(local)\\NetSDK; " +
"Initial Catalog=Northwind;Trusted_Connection=Yes; ";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;
string strRestrictions;
object[] objRestrictions;
objRestrictions = new object[] {null, null, "Customers", null};
DataTable tbl;
tbl = en. Get01eDfaSchemaTable(01eDbSchemaGiJid. Columns, objRestrictions);
Restrictions
OleDbSchemaGuid MSDN.
GetOleDbScbemaTable DataTable (
6), . DataTable . ,
GetOleDbSchemaTable:
Visual Basic .NET
tbl = en. Get01eDbSchemaTable( OleDbSchemaGuid. Columns, strRestrictions)

58

II

: .NET

Console.WriteLineC'Columns in Customers table:")


For Each row In tbl.Hows
Console.WriteLlneCvbTab & row("COLUMN_NAME").ToStringO)
Next row

Visual C# .NET
tbl = en.Get01eDbSchemaTable(01eDbSchemaGuld.Columns, strRestfictions);
Console.WriteLineC'Columns in Customers table:");
foreach(DataRow row in tbl.Rows)
Console. WriteLine("\t" + row["COUJMN_NAME"].ToString());

, GetOleDbSchemaTable (, , ..), , Server Explorer.


GetOleDbSchemaTable OLE DB,
OleDbConnection. He . , OLE DB, .

Visual Studio .NET,



Visual Studio .NET ,
Connection .

Connection Server Explorer


ADO.NET
,
, Visual Studio .NET , .
Server Explorer.
Server Explorer
. . 3-5 Server Explorer
, ,
. Server Explorer
,
Visual Studio .NET, ,
.
, , Event Logs Server Explorer
,
Server Explorer Visual Studio,
, Server Explorer , SQL Server. , Server Explorer Data Connections.

59

'% KEP5ERVEP
& SCEP5ERVER\NE7S:
"A SC?iRVR1,VSRe

. 3-5. Visual Studio .NET Server Explorer


2 Data Form Wizard,
.
Visual Studio Data Connections Server Explorer (. 3-6).

-6.

Data Connections Server Explorer

, . , . , , Oracle SQL Server . , Oracle . Server Explorer.


, .
, Properties .
, Retrieve Data From Table. Server Explorer
. ,

60

II : .NET

, Server Explorer , .
Visual Studio .NET Enterprise Edition SQL Server Oracle. , , , , SQL Server
Oracle.

Server Explorer
Server Explorer,
Server Explorer . (. 3-7),
Data Form Wizard.

. 3-7.
Server Explorer Data Link Properties

. , , ,
, -,
,
, , . , :
*, , , . , ,
.
OLE DB, ODBC .NET
Server Explorer . , , . , -

61

, , ODBC .NET. OLE


DB SQL Server.
Data Link Visual Studio 6. , ADO, OLE DB,
Providers Data Link OLE DB , SQL Server,
Oracle Microsoft Access.
OLE DB , ODBC ODBC.
- , ODBC,
OLE DB.
OLE DB, Microsoft, , OLE DB ODBC. ODBC ADO,
OLE DB.
Providers Data Link Microsoft OLE DB Provider For ODBC Drivers.
Connection, ODBC ODBC.
, Data Link )-- , OLE DB ODBC. .NET? , Data Link
Visual Studio 6. Visual Studio .NET , .NET, . , Server Explorer , OLE DB ODBC.

Data Link Test,
. Data
Link , Allow Saving Password. , ,
. 3-8.

. 3-8. ,

, Server Explorer
. ,
Server Explorer . .

62

II

: .NET

Microsoft ,
. Visual Studio .NET (managed
code), , . .
. ,
.
, .
.

, ? ,
SQL Server, .
- ,
Windows, Windows NT . . , . ,
.
SQL
Server Administering SQL Server\Managing Security\Security Levels\Authentication Modes* SQL Server Books Online.


, Server Explorer, ,
Server Explorer Connection . . Server Explorer
, .
Connection.

Visual Studio .NET, Windows-,
, Web- Web- ASP.NET, .
Windows- ,
.. Properties.
,
, Visual Basic Microsoft Visual InterDev.
, , , , ,
, ? Visual Basic
, ,
, . Visual Studio -NET .
. Properties,

S3


Server Explorer ,
Connection .
, Server Explorer. SQL
Server SqlConnection,
OleDbConnection.
Server Explorer
, ODBC, . OLE DB
Provider for ODBC Drivers. , OdbcConnection ( Connection ODBC
.NET) Visual Studio.
. 3-9 ,
Server Explorer Windows-.
MirmsnH VisualBosis .MM [ itestrai] - Fofmj.i* )1.'.|

6*f

tfOtsa

e*;

Qtbug

* :

Data

IBJ

..,.

Forml.vb [Design
Solutran 1Wrp*jHi(Blic4ncinll (1 profit
^p WkidowtAppkcatianl
3 -ifo.
^ Poml -iti

. 3-9.

SqlConnection Visual Studio .NET

SQL Server, SqlConnection. Visual Studio .NET . Connection .


ConnectionString , ,
Server Explorer.
Connection
Connection , Data
Visual Studio .NET. ,
Connection .NET . . 3-10 -

64

II

: .NET

OleDbConnection,
.
'Properties

} QleDbConnectionl System. Data. leOb.OleDbConnecti on J

"; (DynarrilcPropertiw)
' -'-[ (Name)

OleDbCoraii'ctionl
SCEPSERVER .Norttmnd, dbo

Modifier?
Connections): ring
. information used to

. 3-. Properties
: , ... .
Connection .NET ConnectionSiting. Properties . Visual Studio .NET
Properties ConnectionString
Server Explorer . <New Connection.^. ,
Data Link.


,
. Windows-
. , Visual Studio ,NET
Click . :
Visual Basic .NET
SqlConnectionl.Open(}
MessageEtox.ShowC'Connection opened successfully!")

SqlConnectionl.Closef)
MessageBox.Show("Connection closed successfully!")

Visual C# .NET
SqlConnectionl .Open();
MessageBox.Show("Connection opened successfully!");
SqlConnectionl.Closef);
MessageBox.Show("Connection closed successfully!");

$5

OleDbConnection,
SqlConnection, SqlConnection!
OleDbConnection 1.
.
, .

?
, . SqlConnection
, ,
. . 3-11. SqlConnection'!
Mkramfl luaHJflvfc NfTfdesil;! (onnl.vh
git

Ed*

:\

B""*

FTnect

loots

ijjidora

Jem(i) ^'.

. 3-11*
Visual Studio .NET , (, SqlConnection ),
InitializeComponent .
Windows Form Designer Generated Code (. 3-).
. -,
, . Ifpn
+>. .
-, , Microsoft .
Visual Studio .NET,
, . ,
. . 3-12, Windows Forms Designer .

66

II : .NET

If I^JFurniL

^3 'i*Bullonl_aid(
friend it vests Button! .Hindoos.Forraa.Bi

Hejuitfid ? tbe 'jLnoloMS fots. Dtssigiitt

He.But-t-Bnl Kf-~3 System. Uindoua.?c


. Suapendbayout: [ I

. 3-12.

. Windows Forms Designer

, Windows Forms Designer,


. Microsoft ,
, , , , , .
? , . .
, ? , . , .

OleDbConnection
'* 38.
ADO.NET,
. ,
Connection . , ,
. -
, .
,
OleDbConnection.

67

OleDbConnection
OleDbConnection, , ConnectionString. , OleDbConnection Open . . 3-1
OleDbConnection.
3-1. OleDbConnection

ConnectionString
ConnectionTimeout

Database
DataSource
Provider

Sen-'erVersion
State


String

, OleDbConnection
Int$2
( ), OleDbConnection (
)
String
. /
( )
String
, / ( )
String
OLE DB,
OleDbConnection
( )
String
(
)
ConnectionState
OleDbConnection ( ) ( )

ConnectionString
, OleDbConnection .
ConnectionString , Connection
. , .
ConnectionTimeout
( ), OLE DB
.
,
. , Microsoft OLE DB Provider for SQL Server , Microsoft Jet 4.0 OLE DB Provider
Microsoft OLE DB Provider for Oracle .
OLE DB ? Connect Timeout .
Microsoft OLE DB Provider for SQL Server
Connect Timeout:
"Provider=SQLOLEDB; Data Source=(local)\NetSDK;Initial Catalog=Northwind;
Trusted Connection=Yes; Connect Tirneout=11;"

68

II

: .NET

Connect Timeout
OLE DB , Open
QleDbConnection .
Database DataSource
; . Connection . ?
, , , ,
Data Source, .
DataSource Connection , ;
, SQL Server Oracle, DataSource , . ,
Access, DataSource .
, OLE DB SQL Sewer, , Data Source SQL Server.
SQL Server, DataSource
.
Database'?
, , SQL Server.
SQL Server Initial
Catalog.
ODBC SQL Server
Database. OLE DB SQL
Server Database Initial Catalog .

Provider
QleDbConnection Provider,
OLE DB, . OdbcConnection
, Drii'er,
ODBC . SqlConnection
SQL Server, ,

Serve/Version
. ,
SQL Server XML-.
ServerVersion ,
. ServerVersion
, . ,
SQL Server, SELECT @@Version. ServerVersion
, , .
, SQL Server
OLE DB, ODBC SQL .NET -

69

SQL Server 2000 .


. , ,
:
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB; Data Source=(local)\NetSDK; " &
"Initial Catalog=Northwind; Trusted_Connection=Yes; "
Dim en As New 01eDbConnection{strConn)
cn.OpenQ
If cn.ServerVersion >= "08" Then
'

End If
Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local}\\NetSDK; " +
"Initial Catalog=Northwind;Trusted_Connection=Yes; ";
OleDbConnection en = new OleDbConnection(strConn);
cn.0pen();
if (cn.ServerVersion >= "08") {
//

State
ConnectionState SystemData. . 3-2 , .
3-2.

Broken

16

Closed
Connecting

0
2

Executing

Fetching

Open

. ,
- ( ,
..) .
ADO.NET

. ADO.NET

.
ADO.NET
.
ADO.NET

ConnectionState , ADO.NET.
State Connection Open Closed. -

70

II : .NET

, , , ;
, .
, State ,
StateCbange Connection.

OleDbConnection
3-3 OleDbConnection. , .NET Framework, GetType ToString,
.
3-3. OleDbConnection

BegiriTransaction
CbangeDatabase
Close
CreateCommand
GetOleDbSchemaTable
Open
ReleaseQbjectPool




OleDbCommand


OLE DB

Beg/n Transaction
( , ,
,
) BeginTramaction
Connection. Transaction (
10, ),
, ADO, RDO
, , , Connection
. ADO.NET BeginTransaction Transaction. , Commit
Rollback .
BeginTransaction , , Connection . :
Visual Basic .NET
Dim txn As OleDb.QleDbTransaction = cn.BeginTransaction()

Dim txn As New OleDb.OleDbTransactionO


txn.Connection = en
txn.BeginO

71

Visual C# .NET
OleDbTransaction txn = cn.BeginTransaction{);

OleDbTransaction txn = new OleDbTransactionO;


txn.Connection = en;
txn.Begin();
ChangeDatabase
, SQL Server . SQL Server , , :
USE Northwind

ADO.NET . ChangeDatabase Connection .


:
Visual Basic .NET
Dim en As New QleDbConnection(strConn)
cn.0pen{)
en.ChangeDatabase{"Northwind")

Dim en As New OleDbConnection(strConn)


cn.OpenQ
Dim cmd As OleDbCommand = cn.CreateCommandO
cmd.CommandText = "USE Northwind"
cmd.ExecuteNonQueryO

Visual C# .NET
OleDbConnection en = new OleDbConnection(strConn);
cn.0pen();
en.ChangeDatabase("Northwind");

OleDbConnection en = new OleDbConnection(strConn);


cn.OpenO;
OleDbCommand cmd = cn.CreateCommandO;
cmd.CommandText = "USE Northwind";
cmd.ExecuteNonOueryC);

72

: .NET

Close
Close Connection. :

.
Close Connection, , .
CreateCommand
Command.
Command, Connection
Connection, Command.
:
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB; Data Source=(local)\NetSDK;" &
"Initial Catalog=Nortnwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnectlon(strConn)
Dim cmd As OleDb.OleDbCommand = cn.CreateCommand()

Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &


"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
Dim cmd As New OleDb.OleDbCommandO
cmd.Connection = en

Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new QleDbConnection(strConn);
OleDbCommand cmd = cn.CreateCommand();


string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
OleDbCommand cmd = new OleDbCommandO;
cmd.Connection = en;
GetOleDbSchemaTable
. (, , ..),
GetOleDbSchemaTable OleDbScbemaGuid.
GetOleDbScbemaTable Restrictions,
. ,
, -

73

. Restrictions . .
, Restrictions:
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB;Data Source={local)\NetSDK; " &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.Openf)
Dim tbl As DataTable
tbl = en.GetOleDbSchemaTablefOleDbSchemaGuid,Tables, Nothing)
Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local}\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;
DataTable tbl;
tbl = en,GetOleDbSchemaTableCOleObSchemaGuid.Tables, null);
, Restrictions . MSDN, , Restrictions Table OleDbScbemaGuid :
{"^",

"_",

"_",

"."}

, Customers:
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSDK" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.OpenO
Dim objRestrictions As ObjectO
objRestrictions = New ObjectO {Nothing, Nothing, "Customers", Nothing}
Dim tbl As DataTable
tbl = en.GetQleDbSchemaTable(01eDbSchemaGuid.Columns, objRestrictions)
Visual C# .NET
n

string strConn = "Provider=SQLOLEDB; Data Source=(local)\\NetS K;" +


"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;
string strRestrictions;
object[] objRestrictions;
objRestrictions = new object[] {null, null, "Customers", null};

4-5956

74

II

: .NET

DataTable tbl;
tbl = en.Get01eDbSchemaTable(01eDbSchemaGuid.Columns, objRestrictions);

Restrictions
OleDbScbemaGuid MSDN.
GetOleDbSchemaTable DataTable ( ), . DataTable . ,
GetOleDbSchemaTable:

Visual Basic .NET


tbl = en.GetOleDbSchemaTableCOleDbSchemaGuid.Columns, strRestrictions)
Console.WrlteLine("Columns in Customers table:")
For Each row In tbl.Rows
Console.WriteLine(vbTab & row("COLUMN_NAME").ToString(})
Next row

Visual C# .NET
tbl = en.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, strRestrictions);
Console.WriteLine("Columns in Customers table:");
foreach(DataRow row in tbl.Rows)
Console.WriteLine("\t" + row["COLUMNJME"].ToString());
, GetOleDbSchemaTable (, ,
..) , Server Explorer.
GetOleDbSchemaTable
OLE DB, OleDbConnection. He . , OLE DB, .


Open Connection.
, ConnectionString.
, Connection .
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSOK;" &
"Initial Catalog=Northwind;TrtJSted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
Try
cn.0pen()
Catch ex As Exception
Console.WriteLineC"Attempt to connect failed!" & vbCrLf & ex.Message)
End Try

75

Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleObConnection en = new OLeDbConnection(strConn);

try
{
cn.OpenO;

}
catch (Exception ex)
{
Console.WriteLine{"Attempt to connect failed!\n" + ex.Message);
}

Open Connection, . ,
, ,
, .
, , Connection
, ,
.
ReleaseObjectPool
OLE DB .
ReleaseObjectPool Connection
OleDbConnection, .
, . - Visual
Studio .NET ReleaseObjectPool, ,
. ,
.
:
OLE DB Servlces=-4;
Close OleDbConnection
, .

OleDbConnection
OleDbConnection InfoMessage StateCbange
(. 3-4).
3-4. OleDbConnection

InfoMessage
StateChange

, Connection

State OleDbConnection

76

II

: .NET

InfoMessage
, SQL Server, . SQL Server
PRINT.
.
InfoMessage Connection , .
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB; Data Source=(local)\NetSDK; " &
"Initial Catalog=Northwind;Trusted_Connection=Yes; "
Dim en As New 01eDbConnection{strConn)
AddHandler en. InfoMessage, AddressOf cn_InfoHessage
cn.OpenO
With cn.CreateCommandO
.CommandText = "PRINT 'Hello ADO. NET!'"
. ExecuteNonQueryC )
End With
Public Sub cn_InfoMessage(ByVal sender As Object,
ByVal e As System. Data. OleDb.OleDblnfoMessageEventArgs)
Console, WriteLineC'InfoMessage event occurred")
Console. WriteLinefvbTab & "Message received: " & e. Message)
End Sub

Visual C# .NET
string strConn = "F'rovider=SQLOLEDB; Data Source=(local)\\NetSDK; " +
"Initial Catalog=Northwind;Trusted_Connection=Yes; ";
OleDbConnection en = new OleDbConnection(strConn);
en. InfoMessage += new OleDblnfoMessageEventHandlertcn^InfoHessage);
cn.OpenO;
OleDbCommand cmd = cn.CreateCommandO;
cmd. CommandText = "PRINT 'Hello ADO. NET"';
cmd. ExecuteNonQueryO;
static void cn_InfoMessage(object sender, OleDblnfoMessageEventArgs e)
<
Console. WriteLineC'InfoMessage event occurred");
Console. WriteLine< "\tMessage received: " + e. Message);

;
SQL Server RAISERROR.
, 10.
SQL Server Books Online.

7/

Visual Basic .NET,


Visual Basic .NET , - . ,
, Addttandler, ,
,
.
. 3-13 Visual Basic. ,
. Dim WithEvents. ,
, Visual Basic .NET,
.

%! Mudufel.vfa |

ule Hodulel
Dial UlthEve
sub HeinO
en - 01
cn.QpenO
cn.ciosei;
Sub

. 3-13. Visual Basic .NET


.
, . ,
QleDbConnection. , ,
.
, Visual Basic .NET , ,
,
. ,
WitbEvents; , . . .
:
. . .

78

II : .NET

'
Dim WithEvents en As QleObConnectlan
Dim strCorvn As String * "Provider*SQlQLEDB;Data SQurce==(local)\NetSDK;" &
"Initial Catalog=Northwlnd;Trusted^ConnectiORi=Yes;
en = New QleDbGonnectiorKstrConn)
AddHandler cn.StateChange, AddressQf cn_StateChange
cn.GpenO
Public Sufr erv_StateChange(ByVal sender AS Object, _
8yVal e As System. Data. StateChange Event A rgs)
Console. VfriteLlne("StateChaRge event occurred")
Console, WriteUne(vbTab & "From " & e.OriginalState.ToString)
Console. WriteUf}e<vbTab & "To " i e.CurrentState.ToString)
End Sub

StateChange
, State Connection. , , , .
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSDK; " &
"Initial Catalog=Northwind;Trusted_Connection=Yes; "
Dim on As New QleDbConnection(strConn)
AddHandler en. StateChange, AddressOf cn_StateChange
cn,0pen()
cn.CloseO
Public Sub cn_StateChange(ByVal sender As Object,
ByVal e As System. Data. StateChangeEventArgs)
Console. WriteLineC "StateChange event occurred")
Console. WriteLinefvbTab & "From " & e.OriginalState.ToString)
Console. Writeline(vbTab & "To " & e.CurrentState.ToString)
End Sub

Visual C# .NET
string strConn = "Provider=SQLOLEDB; Data Source=(local)\\NetSDK; " +
"Initial Catalog=Northwind;Trusted_Connection=Yes; ";
OleDbConnection en = new OleDbConnection(strConn);
en. StateChange += new StateChangeEventHandler(cn_StateChange);
cn.0pen();
cn.CloseO;
static void cn_StateChange(object sender, StateChangeEventArgs e)
{
Console. Writel_ine( "StateChange event occurred");

79

Console.WriteLine{"\tFrom " & e.OriginalState.ToStringO);


Console.WrlteLine("\tTo " i e.CurrentState.ToStringO);
i

,
. Server Explorer, ,
, Visual Studio .NET .
Server Explorer?
. Server Explorer . Visual Studio .NET , Server Explorer , (Default
View).SEView. Settings
. , NTFS,
, .
. , SQL Server . ?
. . , SQL Server. ,
,

. (
Web- +) . .
, . .
, ? ,
, ,
. ,
.
, . . , .
,
.
SQL
Server Books Online.

80

II

: .NET

. Connection . Server Explorer,


. Connection,

?
. Server Explorer . ,
.
, .

Connection Microsoft ADO.NET.


Command ADO.NET.
,
Command. - ADO.NET DataReader
Parameter. , . ,
Command Microsoft Visual
Studio .NET. , ,
Command, DataReader Parameter.

Command
Command .
, . , Command .

Command
Command. New . Connection.
CreateCommand Connection ( 3):

82

II

: .NET

Visual Basic .NET


Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT CustomerlD, CompanyName FROM Customers"
Dim en As New OleDbConnection(strConn)
cn.OpenO
Dim cmd As OleDbCommand
cmd = cn.CreateCommandO
cmd.CommandText = strSQL
cmd = New OleDbCommandO
cmd.ConimandText = strSQL
crad.Connection = en
cmd = New OleDbCommand(strSQL, en)

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT CustomerlD, CompanyName FROM Customers";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;
OleDbCommand cmd;
cmd = cn.CreateCommandO;
cmd.CommandText = strSQL;
cmd = new OleDbCommandO;
cmd.CommandText = strSQL;
cmd.Connection = en;
cmd = new 01eQbCommand(strSQL, en);

,
, ,
(action query). .
:
DML- (Data Manipulation Language, ).
(query-based updates.
QBU), . DML-:
UPDATE Customers SET CompanyName = 'NewCompanyName'
WHERE CustomerlD = 'ALFKf
INSERT INTO Customers (CustomerlD, CompanyName)

83

VALUES ('NewID , 'NewCustomer'}


DELETE FROM Customers WHERE CustomerlD = 'ALFKI

DDL- (Data Definition Language, ).


:
CREATE TABLE Tablel (Fieldl int NOT NULL
CONSTRAINT PKJablel PRIMARY KEY,
Field2 varchar(32))
ALTER VIEW Viewl AS SELECT Fieldl, Field2 FROM Tablel
DROP PROCEDURE StoredProcedurel
Command,
Connection , CommandText
ExecuteNonQuery:

Visual Basic .NET


Dim en As New OleDbConnectionO
cn.ConnectionString = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
cn.OpenC)
Dim cmd As OleDbCommand = cn.CreateCommand()
cmd.CommandText = "UPDATE Customers SET CompanyName = 'NewCompanyName'" &
" WHERE CustomerlD = 'ALFKI'"
cmd,ExecuteNonQueryC)

Visual C# .NET
OleDbConnection en = new OleDbConnectionO;
cn.ConnectionString = "Provider=SQLOLEDB; Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
cn.OpenO;
OleDbCommand cmd = cn.CreateCommand();
cmd.CommandText = "UPDATE Customers SET CompanyName = 'NewCompanyName' " +
"WHERE CustomerlD = 'ALFKI1";
cmd.ExecuteNonQueryC);

, ExecuteNonQuery , * ,
. ,
, ( ).
. , , :
CREATE TABLE NewTable (NewTablelD int NOT NULL
CONSTRAINT PKJJewTable PRIMARY KEY,
OtherField varchar(32))

84

II

: .NET

, , . , ,
, .
, , . , :
UPDATE Customers SET CompanyName = 'NewCompanyName'
WHERE Customer^ = 'ALFKI'

, . , ,
WHERE,
. .
, ?
Microsoft SQL Server Query Analyzer, , :
(1 row(s) affected)
: - - ,
, WHERE, ,
.
Command
ExecuteNonQuery, :
Visual Basic .NET
Dim strConn As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New GleDbConnection(strConn)
cn.OpenQ
Dim cmd As OleDbCommand = en.CreateCommandO
cmd.CommandText = "UPDATE Customers SET CompanyName = 'NewCompanyName'" &
" WHERE CustomerlD = 'ALFKI 1 1 1
Dim intRecordsAffected As Integer = cmd.ExecuteNonQuery()
If intRecordsAffected = 1 Then
Console.WriteLineC"Update succeeded"}
Else
' intRecordsAffected = 0
Console.WriteLine("Update failed")
End If

Visual C# .NET
string strConn;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +

85

"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;
OleDbCommand cmd = cn.CreateCommand();
cmd.CommandText = "UPDATE Customers SET CompanyName = 'NewCompanyName' " +
"WHERE CustomerlD = 'ALFKI 1 ";
int intRecordsAffected = cmd.ExecuteNonQueryO;
if (intRecordsAffected == 1)
Console.WriteLineC"Update succeeded");
else
// intRecordsAffected = 0
Console.WriteLine("Update failed");

, , ,
. ExecuteNonQuery
. DML-, , ExecuteNonQuery
-1. , DML- .
, WHERE
. Customer
CustomerlD, CustomerlD . , .


DataReader
, , ?
Command ExecuteReader, DataReader, .
DataReader .NET Framework,
, XmlReader, TextReader StreamReader. , ( )
. , TextReader ,
DataReader .
, RDO, ADO API- ODBC OLE DB, (firehose cursor). , . . , . , , . DataReader ADO.NET
. DataReader, ExecuteReader
Command.

86

II

: .NET


DataReader :
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" i _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleubConnection(strConn)
cn.Openf)
strSQL = "SELECT CustomerlD, CompanyName FROM Customers"
Din cmd As New 01eDbCommand(strSQL, en)
Dim rdr As OleDbDataReader = cmd.ExecuteReaderO
While rdr.ReadO
Console.WriteLine(rdr("CustomerID") & " - " & rdr("CompanyName"))
End While
rdr.CloseO

Visual C# .NET
string strConn, strSOL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenC);
strSQL = "SELECT CustomerlD, CompanyName FROM Customers";
OleDbComraand cmd = new 01eObCommand(strSOL, en);
OleDbDataReader rdr = cmd. ExecuteReaderO;
while (rdr.ReadO)
Console.WriteLine(rdr["CustofneriD"] + " - " + rdr["CompanyName"]);
rdr.CloseO;

:
Read, ExecuteReader .
ADO.NET , ADO. DataReader, Command, Read,
Read DataReader , ,
Read , ,
DataReader . , True, DataReader
; False .

DataReader Item. Item CustomerlD CompanyName . .
.

87


. , DataReader , . : DataReader
.
, .
,
. , ADO . , ,
, .
,
(, ) .
-
.
,
. DataReader . GetOrdinal ,
, ,
. ADO.NET;
, .
, DataReader, GetOrdinal

. ,
. . .
.

Visual Basic .NET


Dim rdr As OleDbDataReader = cmd.ExecuteReaderO
Dim intCustomerlDOrdinal As Integer = rdr.GetOrdinal("CustomerID")
Dim intCompanyNameOrdinal As Integer = rdr.GetOrdinal("CompanyName")
While rdr.ReadO
Console.WriteLine(rdr(intCustornerIDQrdinal) & " - " & _
rdr(intCoropanyNameOrdinal))
End While
rdr.CloseO

Visual C# .NET
OleDbDataReader rdr = cmd.ExecuteReaderO;

88

II : .NET

int intCustomerlDOrdinal = rdr.GetOrdinal("CustomerID");


int intCompanyNameOrdinal = rdr.GetOrdinal{"CompanyName");
while (rdr.ReadO)
Console.WriteLine(rdr[intCustomerIDOrdinal] + " - " +
rdr[intCompanyNameOrdinal]};
rdr.CloseO;
...
, Get
DataReader ,
.NET Framework (string, Int32, double ..).
Item, Object.
, ,
Object . CustomerlD CustomerName , GetString DataReader :
Visual Basic .NET
Dim rdr As OleDbDataReader = cmd.ExecuteReader()
Dim intCustomerlDOrdinal As Integer = rdr.GetOrdinal("CustomerID")
Dim intCompanyNameOrdinal As Integer = rdr.GetQrdinalC'CompanyName")
While rdr.HeadO
Console.WriteLine(rdr.GetString(intCustomerlDOrdinal) & " - " & _
rdr.GetString(intCompanyNameOrdina,D)
End While
rdr.CloseO
Visual C# .NET
OleDbDataReader rdr = cmd.ExecuteReaderO;
int intCustomerlDOrdinal = rdr.GetOrdinal("CustomerID");
int intCompanyNameOrdinal = rdr.GetOrdinal("CompanyName">;
while (rdr.ReadO)
Console.WriteLine(rdr.GetString(intCustomerlDOrdinal) + " - " +
rdr.GetString(intCompanyNameOrdinal)};
rdr.CloseO;
Get,
, . , Order Details Northwincl OrderlD ProductID
. , ,
Getlnt32. 32,
.

89


, SQL Server, , . ,
Northwind :
SELECT CustomerlD, CompanyName, ContactName, Phone FROM Customers;
SELECT OrderlD, CustomerlD, EmployeelD, OrderDate FROM Orders;
SELECT OrderlD, ProductID, Quantity, UnitPrice FROM [Order Details]

, DataReader,
, Read False.
,
.
DataReader NextResttlt,
, . Read , , ,
. Read, NextResult .
Read False, , , NextResult. False, .
NextResult.
Visual Basic .NET
cn.0pen()
Dim strSQL As String
strSQL = "SELECT CustomerlD, CompanyName FROM Customers;" &
"SELECT OrderlD, CustomerlD FROM Orders;" & _
"SELECT OrderlD, ProductID FROM [Order Details]"
Dim cmd As New 01eDbCommand(strSQL, en)
Dim rdr As OleD&DataReader = cmd.ExecuteReaderC)
Do
Do While rdr.ReadO

Console.WriteLine(rdr(0) & " - " 4 rdr(t))


Loop
Console.WriteLineO
Loop While rdr.NextfiesultO
Visual C# .NET
cn.Qpen();

string StrSQL = "SELECT CustomerlD, CompanyName FROM Customers;" +


"SELECT OrderlD, CustomerlD FROM Orders;" +
"SELECT OrderlD, ProductID FROM [Order Details]";
OleDbCommand cmd = new 01eDbCommand(strSQL, en);
OleDbDataReader rdr = cmd.ExecuteReaderC);

do

90

: .NET

while (rdr.ReadO)
Console.WriteLine(rdr[0] + " - " + rdr[1]);
Console. WrlteLlneO;
} while (rdr.NextflesultO);


ADO SQL Server ,
, .
OLD DB- SQL Server SQL
Server, , ,
, Recordset , .
. Recordset
. , <-n row(s) affected*, . NextRecordset. , SET NOCOUNT ON,
; ADO
, .
. . , ADO 2jc Visual
Basic:
Visual Basic
Dim en As ADODB.Connection, rs As ADODB.Recordset
Dim strConn As String, strSQL As String
Dim intRecordsAffected As Integer
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Set en = New ADODB.Connection
en.Open strConn
strSQL = "INSERT
"SELECT
"UPDATE
"SELECT

INTO Customers ...;" & _


CustomerlD, CompanyName FROM Customers WHERE ...;"&_
Customers SET CompanyName = ... WHERE ...;" &
CustomerlD, CompanyName FROM Customers WHERE ..."

Set rs = en.Execute(strSQL, intRecordsAffected, adCmdText)


Do Until rs Is Nothing
Debug.Print "rs.State = " & rs.State & vbTab &
"intRecordsAffected = " & intRecordsAffected
Set rs = rs.NextRecordset(intRecordsAffected)
Loop

91

Recordset , intRecordsAffected 1. INSERT, .


NextRecordset, Recordset SELECT. SELECT -
, intRecordsAffected -1. 'NextRecordset Recordset, intRecordsAffected , UPDATE.
NextRecordset SELECT intRecordsAffected -1. NextRecordset
Recordset, Nothing, , , , .
ADO.NET . ADO.NET , ADO.
, DataReader , . , . , .
DataReader
, . RecordsAffected
DataReader . , :
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK; " &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.Openf)
strSQL = "INSERT INTO Customers ...;" & _
"SELECT CustomerlD, CompanyName FROM Customers WHERE ...;" & _
"UPDATE Customers SET CompanyName = ... WHERE ,,.;" &
"SELECT CustomerlD, CompanyName FROM Customers WHERE ..."
Dim cmd As New 01eDbConnnand(strSQL, en)
Dim rdr As OleDbDataReader = cmd.ExecuteReaderO
Do
Console.WriteLinef"RecordsAffected = " & rdr.RecordsAffected)
Do While rdr.ReadQ
Console.WriteLine{vbTab & rdr.GetName(O) & " - " & rdr.GetValue(O))
Loop
Console. WriteLineO
Loop While rdr.NextResult()

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK; " +

92

II

: .NET

"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;
strSQL = "INSERT INTO Customers . . . ; " +
"SELECT CustomerlD, CompanyName FROM Customers WHERE , . . ; " +
"UPDATE Customers SET CompanyName = . . . WHERE . . . ; " +
"SELECT CustomerlD, CompanyName FROM Customers WHERE . . . " ;
OleDbConwand cmd = new 01eObCommand(strSQL, en);
OleDbDataReader rdr = cmd. ExecuteReaderO;
do
{
Console.WriteLine("RecordsAffected = " + rdr.RecordsAffected);
while (rdr.ReadO)
Console.WriteLine("\t" + rdr.GetName[0].ToString() +
" - " + rdr.GetValue[0].ToString());
Console.WriteLine();
}
while (rdr.NextResultO);

, , , ADO.NET ADO.
.
DataReader, ExecuteReader Command, DataReader
SELECT. NextResult,
SELECT.
NexlResult False, , , ; , .
ADO RecordsAffected DataReader, , INSERT
UPDATE . RecordsAffected , , , DataReader.
, ExecuteReader DataReader, RecordsAffected 1. NextResult
2.
, -DML (, CREATE PROCEDURE
1 TABLE) -1.
ADO.NET , ,
DataReader
ADO.NET
DataReader. Connection
DataReader ,
DataReader, , ,
, .

93

, , ,
ADO, . RDO.
Microsoft - .
SQL Server ADO, .
OLE DB: ,
OLE DB- .
, , ADO,
Connection is busy with results from another hstmt.. ODBC , .
, .
(
) ? Microsoft,
. ,
Microsoft
: VBSQL , DAO/Jet , RDO
, ADO ADO.NET
. : , .
-, VBSQL DAO/Jet.
, 100% .
DataReader .
, DataReader Connection,
. - , DataSet - -.

,
, ( ,
) . , :
SELECT COUNT(*) FROM Customers
SELECT CompanyName FHOM Customers WHERE CustomerlD = 'ALFKI'

DataReader DataSet ,
. Command ExecuteScaiar,
. , Object,
:

94

II : .NET

Visual Basic .NET


Dim strConn As String = "Provider=SOLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.0pen()
Dim cmd As OleDbCommand = cn.CreateCommand{)
cmd.CommandText = "SELECT COUNT(*> FROM Customers"
Dim intCustomers As Integer = CInt(cmd, ExecuteScalarO)
cmd.CommandText = "SELECT CompanyName FROM Customers " &
"WHERE Customer-ID = 'ALFKI1"
Dim strCompanyName As String = Convert.ToString(cmd.ExecuteScalar)
Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;
OleDbCommand cmd = cn.CreateCommandO;
cmd.CommandText = "SELECT COUNT(*) FROM Customers";
int intCustomers = Convert.Tolnt32(cmd.ExecuteScalarO};
cmd.CominandText = "SELECT CompanyName FROM Customers " +
"WHERE CustomerlD = 'ALFKI 1 ";
string strCompanyName = Convert.ToString(cmd.ExecuteScalarO);

ExecuteScalar ,
, , , .


, ,
, . 20 , 20
, , ,
. , . , :
SELECT OrderlD, CustomerlD, EmployeelD, OrderDate
FROM Orders WHERE CustomerlD = ?

.
SQL Server .NET ? @. Customer ID :

95

SELECT OrderlD, CustomerlD, EmployeelD, OrderDate


FROM Orders WHERE CustomerlD = eCustomerlD

SQL Server .NET .


, .
Parameter ADO.NET. , Command Parameters. Command, Parameters Parameter, ,
:
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.0pen()
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, OrderDate " i
"FROM Orders WHERE CustomerlD = ?"
Dim cmd As New 01eDbCommand(strSQL, en)
cmd.Parameters.Add{"@CustomerID", OleDbType.WChar, 5)
cmd.Parameters(O).Value = "ALFKI"
Dim rdr As OleDbDataReader = cmd.ExecuteReader{)
Visual C# .NET
string strConn, strSQL;
StrConn = 'Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, OrderDate " +
"FROM Orders WHERE CustomerlD = ?";
OleDbCommand cmd = new 01eDbCommand(strSQL, en);
cmd. Parameters. Add ("laCustomerlD", OleDbType.WChar, 5);
cmd.Parameters[0].Value = "ALFKI";
OleDbDataReader rdr = cmd, ExecuteReaderO;

ExecuteReader, , DataReader, , , .
. ,
, ,
, . , O'Leary
, :
SELECT EmployeelD, LastName, FirstName FROM Employees
WHERE LastName = '0"Leary'

96

II

: .NET

,
. , .


, , .
SQL Server:
CREATE PROCEDURE GetCustomer (@CustomerID nchar(5)> AS
SELECT CustomerlD, CompanyName, ContactName, ContactTitle
FROM Customers WHERE CustomerlD = ^CustomerlD
RETURN

, Oracle, . Oracle
ADO.NET Microsoft.
Command? CommandType .
CommandType: Text, TableDirect StoredProcedure,
CommandType Text. CommandType StoredProcedure, Command,
Command CommandType
Parameters
:
Visual Basic .NET
Dim en As New OleDbConnection(strConn)
cn.0pen()
Dim cmd As OleDbCommand = cn.CreateCommandO
With cmd
.CommandText = "GetCustomer"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("@CustomerID", OleDbType.WChar, 5)
.Parameters(O).Value = "ALFKI"
End With
Dim rdr As OleDbDataReader = cmd.ExecuteReaderO
If rdr.Read() Then
Console.WriteLine(rdr{"CompanyName"))
Else
Console.WriteLine("No customer found")
End If
rcfr.CloseO
en.Closet)

97

Visual C# .NET
OleDbConnection en = new QleDbConnection(strConn);
cn.OpenO;
OleDbCommand cmd = cn.CreateCotnmand{);
cmd.CommandText = "GetCustomer";
cmd.CommandType = CommandType.StoredProcedure;
cmd. Parameters. Add( "Customer-ID", OleDbType.WChar, 5);
cmd.Parameters[0].Value = "ALFKI";
OleDbDataReader rdr = cmd.ExecuteReaderO;
if

(rdr.ReadO)
Console.WriteLine{rdr["CompanyName"]);
else
Console.WrlteLineC'No customer found");
rdr.CloseO;
cn.CloseO;

:
{? = CALL KyStoredProc<?, ?, ?)}

, , , ,
. :
{CALL GetCustomer(?)}

, CommandType. , , , ,
. OleDbCommand
CommandType TableDirect StoredProcedure, . Command
-. , SqlCommand
. ,
, (!
!).
CommandType CommandText
:
Visual Basic .NET
Dim cmd As New OleDbDataAdapterf)
cffld.CommandText = "{CALL GetCustomar(?)}"
cmd.CommandType = CommandType.Text

98

II

: .NET

Visual C# .NET
OleDbDataAdapter cmd = new OleDbDataAdapterC);
cmd.CommandText = "{CALL GetCustomer{?)}";
cmd.CommandType = CommandType.Text;

, SQL Server, , EXEC Query


Analyzer. Command, ,
. , , .


. .
, SQL Server GetCustomer
CREATE PROCEDURE GetCustomer (@CustomerID nchar{5),
@CompanyName nvarchar(40) OUTPUT,
@ContactName nvarchar(30) OUTPUT,
@ContactTitle nvarctiar(SO) OUTPUT) AS
SELECT @CompanyName = CompanyName, ContactName = ContactName,
ContactTitle = ContactTitle
FROM Customers WHERE CustomerlD = @CustomerID
IF &aROWCOUNT = 1
RETURN 0
ELSE
RETURN -1

Command ?
Parameter Direction, ParameterDirection-. ReturnValue, Input, InputOutput Output.
Direction Input. GetCustomer , Direction ,
.
. ,
,
:

Visual Basic .NET


Dim en As New OleDbConnection(strConn)
cn.OpenO
Dim cmd As OleDbCommand = cn.CreateCommandQ
With cmd
.CommandText = "{? = CALL GetCustomerC?, ?, ?, ?)}"

,Parameters.Add("@RetVal", OleDbType.Integer)

99

.Parameters.Add("@CustomerID", OleDbType.WChar, 5)
.Parameters.Add("@CompanyName", OleDbType.VarWChar, 40)
.Paraineters.Add("@ContactName', OleDbType.VarWChar, 30)
.Parameters.Add("@ContactTitle", OleDbType.VarWChar, 30)
.Parameters("@ContactTitle").Direction = ParameterDirection.Output
.Parameters("@RetVal").Direction = ParameterDirection.ReturnValue
.Parameters("@CustomerID").Value = "ALFKI"
.Parameters("@CompanyName"). Direction = ParameterDirection.Output
,ParametersC'eContactName").Direction = ParameterDirection.Output
, ExecuteNonQueryO
If Convert.Tolnt32(.Parameters^"@RetVal").Value) = 0 Then
Console.WriteLine(. Parame1:ers("@CompanyNafne"). Value)
Else
Console.WriteLineC"Customer not found")
End If
End With

Visual C# .NET
QleDbConnection en = new OleDbConnection(strConn);
cn.0pen();
OleDbCoflimand cmd = cn.CreateConnnand();
cmd.CommandText = "{? = CALL GetCustomer(?, ?, ?, ?)}";
cmd.Parameters.Add("@RetVal", OleDbType.Integer);
cmd. Pa ramete rs.Add("<aCustomerID", OleDbType.WChar, 5);
cmd.Parameters.Add("CompanyName", OleDbType.VarWCha, 40);
cmd.Parameters,Add("ContactName", OleDbType.VarWChar, 30);
cmd.Parameters.Add{"@ContactTitle", OleDbType.VarWChar, 30);
cmd.Parameters["@ContactTitle"].Direction = ParameterDirection.Output;
cmd.Parameters["@RetVal"].Direction = ParameterDirection.ReturnValue;
cmd.Parameters["@CustomerID"].Value = "ALFKI";
cmd.Parameters["@CompanyName"].Direction = ParameterDirection.Output;
cmd.Parameters["@ContactName"].Direction = ParameterDirection.Output;
cmd, ExecuteNonQueryO;
if (Convert.ToInt32(cmd.Parameters[TTeRetVal"].Value) == 0)
Console.WriteLine(cmd.Paranteters["@CompanyName"].Value);
else
Console.WriteLineC'Customer not found");


Command Transaction, ,
, .
, Transaction BeginTransaction

100

II : .NET

Command. ,
:
Visual Basic .NET
cn.OpenQ
Dim txn As QleDbTransaction = en.Begin!ransaction()
Dim strSQL As String = "INSERT INTO Customers (...) VALUES (...)"
Dim cmd As New 01eDbCommand(strSQL, en, txn)
Dim intRecordsAffected As Integer = cmd.ExecuteNonQueryO
If intRecordsAffected = 1 Then
Console.WriteLine("Update succeeded")
txn.CommitO
Else
', intRecordsAffected =
Console.WriteLineC"Update failed")
txn.RollbackQ
End If

Visual C# .NET
cn.OpenQ;
QleDbTransaction txn = en.BeginTransaction();
string StrSQL = "INSERT INTO Customers (...) VALUES (...)";
OleDbCommand cmd = new 01eDbCommand(strSQL, en, txn);
int IntRecorbsAffected = cmd.ExecuteNonQueryO;
if (intRecordsAffected == 1)
i
Console.WriteLine{"Update succeeded");
txn.CommitO;
}
else
{
//, =
Console.WriteLine("Update failed");
txn.RollbackO;
i

He Commit Rollback Transaction ( , ,


).

Command Visual Studio .NET


Visual Studio .NET , , Command.
Visual Studio .NET , Command.

101


Command Visual Studio .NET . Data Command .NET. OleDbCommand,
OleDbCommand
. Command (. 4-1).
-N| 1 1 dtsjEnJ f otm! .b [DesiMi]*

iffi (DynnfcProperto
(Name) '.
OleDbCotnm,
CommandText

4\ Modifers
.j! Parem4

Friend
(CcHlecBon)
i Both

. 4-1. OleDbCommand
Command
, Command
. Visual Studio .NET
(Connection CommandText) Comtnantl
.

Connection
Command ,
Connection. Connection Properties, . (Existing)
, (New) Connection
. . 4-2 Windows- OleDbConnection
OleDbCommand . OleDbCommand,
Properties , Connection OleDbConnection.
New, Data Link
Properties, . Visual Studio .NET

102

II

: .NET

Connection, , Connection Command,


3 * "* B-*i *

t(
Darnel

OleDbCommandl

E-Minq

. 4-2.

Connection

Query Builder
Visual Studio .NET Query Builder.
Command
Properties CommandText . , ,
. ,
Query Builder (. 4-3).
Query Builder . Query Builder
, ,
(. 4-3). , Add Table.
. Query Buiider , , .. . 4-4
Customers , . :
CustomerlD.
Query Builder . . .
. , ,
. Verify.

'-i-Kl'-'J.l'J':^-.-

, 4-3.

cdum
1 OfitomerlD
1 OMi^Mriyhang
1 Ccjitattrjarg
| ContactTitle

. 4-4.

U.I

>

!.""

103

<>

T*te

a;
CustM
IJKlDH an
Qblon an
IJKtHI

lOutput
-s
V
V
v"

IbnlTypO

son order

joteia
UKE'

Query Builder

, Run, . , Query Builder . , Query Builder .

104

II

: .NET

Command
Command
:
SELECT CustomerlD, CompanyName, ContactName, ContactTitle
FROM Customers WHERE CustomerlD LIKE ?

, Commands,
, *. ,
. CompanyName
.
, Load.
Command,
DataReader CompanyName . ,
CustomedlD , %, .
Visual Basic .NET . 4-5.
ictosoft USsual Basic .NET [design] - Foiml.vb*

2S

. 4-5. Command
Visual Basic .NET
Visual * .NET :
//
oleDbConnectionl.(};
// ,
//
oleDbCommand1.Parameters[0]. Value = "1;
// CompanyName

105

OleDbDataReader rdr = oleDbCommandl.ExecuteReaderQ;


while (rdr.ReadO)
llstBoxl.Items.Add(rdr["CompanyName"]);
// DataReader Connection
rdr.CloseO;
oleDbConnectionl.Close();
Visual * .NET ! using
using SystemData.OleDb;.
, , Customers.

Server Explorer
Command , Server
Explorer . SQL
Server SqlCommand,
OleDbCommand.
. 4-6 Windows- CustOrderHist
SQL Server North wind. Properties , CommandText,
CommandType Connection ,
. WindowsApaUr.it1

t*liaofi isualB<h; ,NI I Nciienl *pm!l.*hil!esfen1*

? X

Forml.vfa [Dnignl*

/ Northtvintd Ao|

ConrnandTineout
CamrundTvpe
Lonnetii'.

PmdyctfJw

,i

'Modifiers
Paiameteis

30
awcdprocs

frtHid
(follcclion)

Uf-datedRov-Somca BoOl
Err(4i>y ^ala* bv -c
51 by Yew
E) SatoytatP5r4y
E Ten Most Expensive F

. 4-6.

Command

Visual Studio .NET -, ,


, .

5-5958

106

: .NET

Visual Studio .NET Parameters Command.


, Parameters Properties , (. 4-7).
Sq Parameter Collection Editor

Orertiofi

Input

. precision
i Scale
.- SourceCokimn
\ SourceVersion

Current

'Fat' i

Ualue
1

'

i ParametsrPJame

. 4-7 Parameters Command,



Parameters Command, Visual Studio .NET . , SQL Server, - , . ,
,
Properties.
Server Explorer
DataAdapter, Command. DataAdapter
.

Command,
DataReader Parameter
, Command, DataReader
Parameter, .

OleDbCommand
. 4-1
Command.

4
4-1.

IOJ

OleDbCommand

CommandText
CommandTimeout


String
lnt$2

CommandType

CommandType

Connection

QleDbConnectio n

Parameters
Transaction

OleDbParameterCollection
OleDbTransactio n

UpdatedRowSource

UpdateRowSource

,
( ),

( 30 )
(
'Jext)
, Command

,

, DataRoic, Command Update DataAdapter (no Both).

CommandTimeout
CommandTimeout ( ), Command .
30 . , CommandTimeout, , Command .
: ,
. , DataAdapter
DataSet, ,
30 , ..
CommandTimeout Command. Command, DataAdapter,
30 , ,
, .
CommandType
CommandType
(. 4-2) CommandType (
SystemData}.
CommandType Text. mand&in , CommandText. , CommandText
, ,
CommandType TableDirect, Command
Commaridlext SELECT
" FROM. , Command
.

1 08

II

: .NET

4-2. CommandType

Text

StoredProcedure

TableDirect

512

Command
CommandText
Command
, CommandText
Command
CommandText SELECT ' FROM*

, , Order Details Northwind, -, , . , . CommandType


TableDirect, - .
, , ,
, . , , : ,
?
TableDirect , , ADO, , adCmdTableDirect Command ADO. ,
adCmdTable, , CommandType TableDirect, Command , OLE DB-no Jet SQL Server.
StoredProcedure :
Visual Basic .NET
Dim cmd As New OleDbCommandO
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "MyStoredProc"
cmd.CommandType = CommandType.CommandText
cmd.CommandText = "{CALL MyStoredProc}"
Visual C# .NET
QleDbCommand cmd = new OleDbCommandO;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "MyStoredProc";
cmd.CommandType = CommandType.CommandText;
cmd.CommandText = "{CALL MyStoredProc}";

109

{CALL
MyStoredProc}. , SQL Server EXEC My Store dPr .
OLE DB- SQL Server , CALL,
EXEC. ,
EXEC - .
, ,
. , .
TableDirect, CommandType
StoredProcedure,
-.
CommandType CommandText CALL,

Parameters
Parameters OleDbParametersCollection,
OleDbParameter. QleDbParameter .

Transaction
Transaction Command .

Command, Transaction, Command .
UpdatedRowSource
UpdatedRowSource ,
DataAdapter Command, . . 4-3.
UpdatedRowSource 11.
4-3. UpdateRowSource

Both

FirstReturnedRecord

None

OutputParameters

Command ,
Command ,
Command
Command ,

110

II : .NET

OteDbCommand
4-4. OleDbCommand

Cancel

CrealeParameter
ExecuteNonQuery
ExecuteReader

ExecuteScalar

OleDbDataReader


"SELECT COUNT(*) FROM HyTable W H E R E . . . "

Prepare
ResetCommandTimeout


CommandTimeout
30

Cancel
Cancel . Cancel
Command, , .
, Cancel Command DataReader, .
. ,
. Cancel.
, , Cancel
.
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB; Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim strSQL As String = "SELECT CustomerlD FROM Customers"
Dim en As New OleDbConnection(strConn)
cn.0pen{)
Dim cmd As New 01eDbCommand(strSQL, en)
Dim rdr As OleDbDataReader = cmd.ExecuteReader()
Dim intRowsRetrieved As Integer
'cmd.CancelO
Do While rdr.Read
Console.WriteLine(rdr.GetString(O))
intRowsRetrieved += 1
Loop
Console.WriteLine(intRowsRetrieved & " row(s) retrieved")
rdr.Closef)
cn.CloseQ

111

Visual C# .NET
string strConn = "Provider=SQLOLEI)B; Data Source=(local)\\NetSDK; " *"Initial Catalog=Northwind;Trusted_Connection=Yes;";
string strSQL = "SELECT Customerl!) FROM Customers";
OleDbConnection en = new OleDbConnection(strConn);
cn.Openf);
OleDbCommand cmd = new OleDbCommandfstrSQL, en);
QleDbDataReader rdr = cmd.ExecuteHeader();
int intHowsRetrieved = 0;
//cmd.Cancel();
while (rdr.ReadO)
{
Console.WriteLine(rdr.GetString(O));
intflowsRet rieved--;
>
Console.WriteLine{intRowsRetrieved + " row(s) retrieved");
rdr.CloseO;
cn.CloseO;
ExecuteNonQuery
ExecuteNonQuery , DataReader . , .
ExecuteNonQuery,
ExecuteNonQuery ,
, . ExecuteNonQuery .
ExecuteReader
ExecuteReader Command , ,
DataReader. , ,
.
ExecuteReader Command CommandBebavior (. 4-5).
4-5. CommandBehavior

CloseConnection

32

Keylnfo

ScbemaOnly

_^__

DataReader
DataReader

DataReader

. , ,

112

II

4-5.

SequentialAccess

SingleResult
SingteRow

: .NET

()

16

. ,
,

1
DataReader
,
8
DataReader ,

CloseConnection
ExecuteReader CloseConnection,
Close DataReader Close Connection.
, - . , - DataReader, DataTable -
. ,
Connection, DataReader.
, ? . CloseConnection,
,
.
Keylnfo SchemaOnty
DataReader
GetScbemaTable. DataReader , .. .
GetSchemaTable DataReader, Keylnfo
SchemaOnty, ExecuteReader Command.
ExecuteReader Options ScbemaOnfy,
, .
Options Keylnfo, DataReader , ,

.
ScbemaOnfy
Keylnfo . ADO.NET .
SequentialAccess
ExecuteReader CloseConnection,
DataReader
. . ,
.

113

, SequentialAccess
DataReader.
SingieRow SingleResult

,
, ExecuteReader
SingieRow SingleResult .
SingieRow DataReader,
, 10
ExecuteReader SingieRow, DataReader
. . SingleResult .
ExecuteScalar
ExecuteScalar ExecuteReader ,
,
Object.
, .

, ExecuteScalar.
SELECT (-) FROM HyTable

Prepare
,
.
, .
. , , .
;
. , .
Command, Prepare.

. , . , - .
.
-,
. ,
,
, .
.

114

: .NET

, , , ,
. SQL Server ,
.
ResetCommandTimeout
ResetCommandTimeout CommandTimeout
30 . : ?, , .

OleDbDataReader
. 4-6 OleDbDataReader.
4-6.
OleDbDataReader

Depth


Int32

FieldCount

Int32

IsClosed

Boolean

Item

Object

RecordsAffected

32

.

DataReader.

, DataReader.
.
,
.

Depth GetData
Depth GetData ,
, ADO.NET .
FieldCount
FieldCount , .
IsClosed
IsClosed , ,
DataReader.
Item
Item DataReader Item DataRow.
, Item
Object.

115

, ' (, Getlnteger GetString).


RecordsAffected
RecordsAffected ,
.
, , ExecuteNonQuery
Command ,
, , , , .

OleDbDataReader
. 4-7 OleDbDataReader.
4-7.
OleDbDataReader

Close
>
GetBytes
GetCbars
GetData
GetDataTypeName
GetFieldType
GetName
GetOrdinal
GetScbemaTable
GetValue
GetValues
isDBNutt
NextResult
Read

DataReader
,


DataReader




( )
DataReader DataTable

, DataReader .
!nt32,
, NULL

Read
Read . : Read, ,
DataReader, . Read DataReader ,
.

116

II

: .NET

Read , ,
DataReader . , Read False.
GetValue
GetValue Item. Object.
GetValue > , , , Item.
DataReader ,
, , ,
.
1<>
DataReader ,
. , string,
GetValue DataReader
string GetString:
Visual Basic .NET
Dim strCompanyName As String
Dim rdr As OleDbDataReader
strCompanyName = rdr.GetString(intCompanyNamelndex)

'
strCompanyName = rdr.GetValue(intCompanyNameIndex),ToString

Visual C# .NET
string strCompanyName;
OleDbDataReader rdr;
strCompanyName = rdr.GetString(intCompanyNamelndex);

//
strCompanyName = rdr.GetValue(intCompanyNameIndex).ToString();

DataReader .NET
Framework GetByte, GetChar, GetDateTime ..
GetVatues
GetValues . , GetValues , .
DataAdapter DataReader
DataTable. , DataAdapter .NET Visual Studio
.NET GetValues DataReader.

117

Visual Basic .NET


Dim rdr As OleDbDat a Reader = cmd. EixecuteReaderO
Dim aData(rdr.FieldCount - 1) As Object
While rdr.Read
rdr.GetValuesCaData)
Console.WriteLine(aData(0),ToString)
End While

Visual C# .NET
OleDbDataReader rdr = cmd.ExecuteReader();
object[] aData = new object[rdr.FieldCount];
while (rdr.ReadQ)
{
rdr.GetValues(aData);
Console,WriteLine(aData[0].To8tring());

Visual Basic .NET Visual C* .NET - , . ,


Dim aData(4) As Object Visual Basic Visual Basic .NET
(0 4), objectf] aData = new object{4] Visual *. NET (0 3).
NextResult
, ,
NextResult. Read, NextResult , , .
, * , DataReader NextResult .
Close
DataReader
DataReader. Connection
- , ,
. Connection, DataReader. , ,
.
. ADO.NET
Connection DataReader ;
- DataReader , -

118

: .NET

. ,
ADO.NET .
, , , ADO,
, RDO. Microsoft
- .
SQL Server ADO, .
. . , OLE DB-no .
, , ADO,
Connection is busy with results from another hstmt.. ODBC , .
, .
(
) ? Microsoft,
, .
Microsoft ,
: VBSQL , DAO/Jet , RDO . ADO ADO.NET .
GetName, GetOrdinal GetDataTypeName
DataReadcr , . , GetName
.
, GetOrdinal GetDataTypeName , , .
GetSchemaTable
GetSchemaTable DataReader FillSchema
DataAdapter. DataTable DataColumn,
, . GetSchemaTable
- DataTable.
' DataColumn, ,
; Roics . GetSchemaTable
DataTable .
, ,
GetSchemaTable. DataTable . DataRow DataTable
, DataColumn ,
.

119

Visual Basic .NET


Dim strConn, strSQL As String
strConn = "Provider=SQLOLEOB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, OrderDate FROM Orders"
Dim en As New OleQbConnectlon(strConn)
cn.OpenC)
Dim ctnd As New 01eDbCommand(strSQL, en)
Dim rdr As OleDbDataReader = cmd.ExecuteReader
Dim tbl As DataTable = rdr.GetScheraaTable
Dim row As DataRow
For Each row In tbl.Rows
Console.WriteLine(row("ColumnName").ToString & " - " 4 _
CType{row("ProviderType"), 01eDbType).ToString)
Next row

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
StrSQL = "SELECT OrderlD, CustomerlD, EmployeelD, OrderDate FROM Orders";
OleDbConnection en = new QleDbConnection(strConn);
cn.0pen();
OleDbCommand cmd = new 01eDbCommand(strSQL, en);
OleDbDataReader rdr = cmd.ExecuteReader();
DataTable tbl = rdr.GetScnemaTable();
foreacn (DataRow row in tbl.Rows)
Console.WriteLine(row["ColumnName"] + " - " +
((OleDbType) row["ProviderType"]).ToString());
integer, ProviderType,
OleDbType.
.NET DataTable, GetTableScbema, . , GetSchemaTable DataReader SQL Server. NET DataTable.
, OLE DB .NET.
GetData Depth
Depth GetData ,
, ADO.NET .

Parameter
Parameter . ParameterCollection
Add,
Parameter . Para-

120

II : .NET

meter CreateParameter Command.


!
? , .
Parameter . , OleDbParameter ParameterName, OleDbType, Size, Direction, IsNullable, Precision, Scale, SourceColumn, SourceVersion Value. ,
, ,
.

OleDbParameter
. 4-8 OleDbParameter.
4-8.
OleDbParameter

Datatype
DbType
Direction

OleDbType
ParameterDirection

IsNullable

Boolean

OleDbType
ParameterName
Precision
Scale
Size
SourceColumn

OleDbType
ParameterName
Byte
Byte
Int32
String

SourceVersion

DataRoivVersion

Value

Object




(Input), (Output), / (InputOutpuf),
(Return)
, Null
OLE DB




DataSet, .

DataSet 10
( ) DataSet,
. DataSet 10

ParameterName
, ParameterName Parameter
, Parameters
Command. ,
OLE DB .NET, ParameterName Parameter .
ParameterName, ,
.

121

SQL Server .NET


Parameter ,
ParameterName Parameter. ,
SELECT OrderlD, CustomerlD, EmployeelD, OrderDate
FROM Orders WHERE CustomerlD = @CustomerID

ParameterName Parameter
@CustomerID.
Direction
, Direction Parameter , . 4-9.
4-9. ParameterDirection

Input

Output
InputOuipiit
Return

2
-'

.


-

Direction input,
Parameter, .

, .
, Visual Studio
.NET,
Direction Parameter,
** . , ,
- ,
,
. , SQL Server OUTPUT, ,
. , -. , , - . Visual Studio .NET , . , Direction ,
Value
Value .
Object. , , -

122

II

: .NET

Value
, string integer.
SourceCotumn SourceVersion
SourceColumn SourceVersion , Parameter DataRow,
Update DataAdapter.
10.
DbType OfeDbType
Parameter ADO.NET, .
, DataAdapter CustomerlD
Customers DataSet, ,

Unicode. DataColumn string,
DataType DataColumn , ADO.NET
, .NET, GetType typeof(R ).
, . (, char varchar) String .NET,
(money, decimal, numeric) Decimal ..
Parameter .

SELECT OrderlD, CustomerlD, EmployeelD, OrderDate
FROM Orders WHERE CustomerlD = ?

, wchar (w wide
(), , Unicode,
ANSI), 5. , ,
.
Parameter DbType
.NET , . , OleDbPammeter OleDbType, SqlParameter SqlDbType.
DbType OleDbType , .
, DbType OleDbParameter DbTypelnt32,
OleDbType OleDbType Integer. ,
OleDbType OleDbType.UnsignedTinylnt,
DbType DbTypeByte,
Precision, Scale Size
,
. . Parameter , Size

123

. ( ) ( ).

,
. , . , .
?
.
. , . , . , , Command , DataReader.
, :
CREATE PROCEDURE RowsAndOutput (@OutputParam int OUTPUT) AS
SELECT @OutputParam = COUNT(-) FROM Customers
SELECT CustomerlD, CompanyName,

ContactName,

Phone FROM Customers

:
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SGLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwlnd;Trusted_Connection=Yes;"
Dim on As New OleDbConnection(strConn)
cn.OpenO
StrSQL = "{CALL RowsAndOutput(?)>"
Dim cmd As New 01eDbCommand(strSQL, en)
Dim param As OleDbParameter
param = cmd.Parameters.Add("@OutputParam", OleDbType.Integer)
param.Direction = ParameterDirection. Output
Dim rdrCustomers As QleDbDataReader = cmd.ExecuteReader
Console.WriteLine("After execution - " & CStr(param.Value))
Do While rdrCustomers.Read
Loop
Console.WriteLine("After reading rows - " & CStr(param.Value))
Do While rdrCustomers. NextResultO
Loop
Console.WriteLineC'After reading all results - " &
CStr(param.Value))
rdrCustomers.CloseC)
Console.WriteLineC'After closing DataReader - " &
CStrCparam.Value))

124

II : .NET

Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial
Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.0pen();
string strSQL = "{CALL RowsAndOutput(?)}";
OleDbCommand cmd = new 01eDbCommand(strSQL, en);
OleDbParameter param;
param = cmd.Parameters.Add("@OutputPararn", OleDbType.Integer);
pa ram.Direction = ParameterDirection. Output;
OleDbDataReader rdrCustomers = cmd.ExecuteReaderf);
Console.WriteLineC'After execution - " + (string) param.Value);
while (rdrCustomers.ReadO)
{}
Console.WriteLineC'After reading rows - " + (string) param.Value);
while (rdrCustomers.NextResult())
{}

Console.WriteLineC'After reading all results - " +


(string) param.Value);
rdrCustomers.Closet);
Console.WriteLineC'After closing DataReader - " +
(string) param.Value);
,
, , Customers,
DataReader.
. MSDN , DbType - ,
.NET .
? ?
. ADO.NET, , , , ,
. , , .
. , , , , -, .
.
, OleDbParameter,
Value, . , (CustomerlD) .

Visual Basic .NET


Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.0pen()
strSQL = "SELECT CustomerlD, CompanyName FROM Customers " &
"WHERE CustomerlD LIKE ?"
Dim cmd As New 01eDt>Command(strSQL, en)
cmd.Parameters.Add("@CustomerID", "AST)
Dim rdr As OleDbDataReader = cmd.ExecuteReader
Do While rdr.Read
Console.WriteLine(rdr(0))
Loop

rdr.Close()
cn.CloseO

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLQLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
QleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;
StrSQL = "SELECT CustomerlD FROM Customers WHERE CustomerlO LIKE ?";
QleDbComraand cmd = new 01eDbCommand(strSQL, en);
cmd.Pa rameters.Add("@Custome rID", "A*");
OleDbDataReader rdr = cmd.ExecuteReaderQ;
while (rdr.ReadO)
Console.WriteLine(rdr[0]);
rdr.Close();
cn.CloseO;

, , DbType,
OleDbType Size OleDbParameter ^
. OleDbParameter ,
, . SQL
Profiler SQL Server 2000, , Command :
exec sp_executesql
N'SELECT CustomerlD FROM Customers WHERE CustomerlD LIKE @P1',
N'@P1 nvarchar(2)', N ' A X '

OleDbParameter , Unicode , 2 . SQL Server, Oracle Access (, currency'),


.
, .
- -

126

II

: .NET

, . , ,
, ,
.
. ? , ,
. -, DataReader Command, , ,
DataReader ( ).
, . ,
DataReader, .
:
CREATE PROCEDURE GetReturnParameter (faCustomerlD nchar(5)) AS
SELECT OrderlD, Customer!!), EmployeelD, OrderDate
FROM Orders WHERE CustomerlD = @CustomerID
RETURN @@ROWCOUNT

Visual Basic .NET :


Dim cmd As New OleDbCommandC'GetReturnParameter", en)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@CustomerID", OleDbType.WChar, 5}
cmd.Parameters("@CustomerID").Value = "ALFKI"
cmd.Parameters.Add("@RetVal", OleDbType.Integer)
cmd.Parameters("@RetVal").Direction = ParameterDirection.ReturnValue

, . . ,
CommandType StoredProcedure, ,
CommandType ADO.NET
ADO. ADO.NET , , , , ,
.
C'ommandText :
{? = CALL GetReturnParameter(?)}

Visual Basic *. , , .
:
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"

127

Dim en As New OleObConnection(strConn)


cn.OpenO
strSQL = "<? = CALL GetReturnParaineterf?)}"
Dim cmd As New 01eDbCommand(strSQL, en)
cmd.Parameters.Add("@RetVal", OleDbType.Integer)
cmd.Parameters("@RetVal").Direction = ParameterDirection.ReturnValue
cmd.Parameters.Add("@CustoinerID", OleDbType.WChar, 5)
cfnd.Parameters("@CustomerID"). Value = "ALFKI"
Dim rdr As OleDbDataReader = cmd.ExecuteReader
Do While rdr.Read

Console.WriteLine("OrderID = " & rdr(O).ToString)


Loop
rdr.CloseO
Console.WriteLine(cmd.Parameters(O).Value.ToString & " orders")
Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
GleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;
strSQL = "{? = CALL GetReturnParameter(?)}";
GleDbCommand cmd = new 01eDbCofnmand(strSQL, en);
cmd.Parameters.Add("@RetVal", OleDbType.Integer);
cmd.Parameters!! "@RetVal"].Direction = ParameterDirection.ReturnValue;
cmd. Parameters.AddOCustonterlD", OleDbType. WChar, 5);
cmd.Parameters["@CustomerID"]. Value = "ALFKI";
OleDbDataReader rdr = cmd. ExecuteReaderQ;
while (rdr.ReadO)
Console.WriteLine("OrderID = " + rdr[0].ToString());
rdr.CloseO;
Console.WriteLine(cmd.ParameterstO].Value.ToStringO + " orders");
cn.CloseO;

. ADO ADO.NET.
Refresh Parameters ADO,
ParameterCollection ADO.NET?
. Refersh ParameterCollection , , .
ADO.NET .
.
CommandBuilder ( 10) DeriveParameters, Parameters Command,
, , .

128

II : .NET

Visual Basic .NET


Dim strConn As String = "Provider=SQLOLEDB;" & _
Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;" & _
Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.0pen()
Dim cmd As New OleDbCommandC'SalesByCategory", en)
cmd.CommandType = CommandType.StoredProcedure
OleDbCommandBijilder.DeriveParaineters(cmd)
Dim param As OleDbParameter
For Each param In cmd.Parameters
Console.WriteLine(pa ram.ParameterName)
Console. WriteLine(vbTab & param. Direction.ToStringO)
Console.WriteLine(vbTab & param,OleDbType.ToStringO}
Console.WriteLineC)
Next param
cn.CloseO

Visual C# .NET
string strConn = "Provider=SQLOLEDB; Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.QpenO;
QleDbCommand cmd = new 01eDbCommand("SalesByCategory", en);
cmd.CommandType = CommandType.StoredProcedure;
OleDbCommandBuilder.DeriveParameters(cmd);
foreach (OleDbParanieter param in cmd.Parameters)
{
Console.WriteLine(pa ram.ParameterName};
Console. WriteLine("\t" + param.Direction.ToStringO);
Console. WriteL.ine("\'t" + paran.OleDbType.ToStringO);
Console, WriteLineO;
}
cn.CloseO;

. ADO . ADO.NET?
. ADO.NET .
Command ADO ,
, , , Visual Basic , ,
.
,NET Framework ,
, , . - ,
. ,
, . -

129

Visual Basic .NET *, , .


,
. , Cancel Command, . , .
, .
,
. clsSlowQuery,
, . , Cal&lowQuery ,
. , .
, . 2,5
CancelQueiy, .
Visual Basic .NET
' Module'!.vb
Dim obj As New clsSlowdueryO
obj.CallSlowQueryO
Threading. read. Sleep( 2500)
obj. CancelQueryO

*
' clsSlowQuery.vb
Public Class clsSlowQuery
Dim en As OleDbConnectlon
Dim cmd As OleDbCommand
Dim ts As Threading.ThreadStart
Dim th As Threading.Thread
Dim blnRunningQuery, blnCancelledQuery As Boolean
Public Sub CallSlowOueryO
If Not blnRunningQuery Then
SyncLock He
blnRunningQuery = True
ts = New Threading.ThreadStart(AddressOf CallQueryAsync)
th = New Threading.Thread(ts)
th.Startf)
Console.WriteLine("Running query")
End SyncLock
Else
Dim strMessage As String
strMessage = "Can't execute CallSlowQuery method." & _
vbCrLf & _
vbTab i "I'm still waiting on the results " & _

130

II

: .NET

"of a previous query."


Throw New Exception(strMessage)
End If
End Sub
Public Sub CancelQueryO
If blnfiunningQuery Then
SyncLock Me
Try
blnCancelledQuery = True
cmd.Cancel )
Catch ex As Exception
Console.WriteLinefex.Message)
End Try
End SyncLock
Else
Dim strHessage As String
strMessage = "Can't execute CancelQuery method." & vbCrLf &
vbTab & "I'm not currently running a query."
Throw New Exception{strMessage)
End If
End Sub
Private Sub CallQueryAsyncO
Dim strConn As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim strSQL As String = "WAITFOR DELAY '00:00:10';" & _
"SELECT Count(-) FROM Customers"
en = New OleDbConnection(strConn)
cn.0pen()
cmd = New QleDbCommand{strSQL, en)
Dim intNumCustomers As Integer
Try
intNumCustomers = Clnt(cmd.ExecuteScalar)
Console.WriteLine(intNumCustomers)
Catch ex As Exception
If blnCancelledQuery = True Then
Console.WriteLine("Query cancelled")
Else

Console.WriteLine(ex.Message)
End If
End Try
cn.CloseO
blnRunningQuery = False
blnCancelledQuery = False
End Sub
End Class

Visual # .NET
// Class1.cs
clsSlowQuery obj = new clsSlowQueryO;
obj.CallSlowQueryQ;
System. Th reading . Th read . Sleep( 2500 ) ;
obj .CancelQueryQ;
// clsSlowQuery. cs
public class clsSlowQuery
{
OleDbConnection en;
OleDbCommand cmd;
System. Th reading. ThreadStart ts;
System. Threading. Thread th;
bool blnRunningQuery, blnCancelledQuery;
public void CallSlowQueryO
I
if (IblnRunningQuery)
lock (this)
{
blnRunningQuery = true;
ts = new
System. Threading. ThreadStart (this. CallQueryAsync};
th = new System, Threading. Thread(ts);
th.StartO;
Console. WriteLine( "Running query"};
else
string strMessage;
strMessage = "Can't execute CallSlowQuery method. \n\t" +
"I'm still waiting on the results " +
"of a previous query.";
throw new Exception{st rMessage);
I

public void CancelQueryO


i
if (blnRunningQuery)
lock(this)
try
blnCancelledQuery = true;
cmd.CancelO;

131

132

II

: .NET

}
catch (Exception ex)
<
Con sole. Write Line (ex. Message);
else
string strMessage;
strMessage = "Can't execute CancelQuery method. \n\t" +
"I'm not currently running a query.";
throw new Exception(strHessage);

private void CallQueryAsyncO


{
string strConn;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK; " +
"Initial Catalog=Northwind;Trusted_Connection=Yes;
string strSQL = "WAITFOR DELAY '00:00:10';" +

"SELECT Count(-) FROM Customers";


en = new OleDbConnection(strConn);
en, Open();
cmd = new 01eDbCommand(strSQL, en);
int intNumCustomers;
try
*

intNumCustomers = (int) cmd. ExecuteScalarO;


Console. WriteLineC intNumCustomers);

!
catch (Exception ex)
:
if (blnCancelledQuery)
Console. WriteLine( "Query cancelled");
else
Console. WriteLine( ex. Message);

cn.CloseO;
blnRunningQuery = false;
blnCancelledQuery = false;

5


DataAdapter

1\ 4, Command DataReader . , DataSet ADO.NET? , DataSet ,


DataReader.

Visual Basic .NET


Dim ds As New DataSetO
Dim tbl As DataTable = ds.Tables.Add("Customers")
' DataTable
Dim cmd As New OleDbCommandO
' Command
Dim rdr As OleDbDataReader = cmd.ExecuteReader()
Dim row As Dataflow
Do While rdr.ReadO
row = tbl.NewRow()
row( "Customer-ID") = rdr("CustomerID")
'
tbl.Rows.Add(row)
Loop
rdr.CloseO

134

II

: .NET

Visual C# .NET
DataSet ds = new DataSetO;
DataTable tbl = ds.Tables.AddC'Customers");
// DataTable
OleDbCommand cmd = new OleDbCommandO;
// Command
OleDbDataReader rdr = cmd.ExecuteReader{);

DataRow row;

while (rdr.ReadO)
I
row = tbl.NewRowO;
row["CustomerID"] = rdr["CustomerID"];
//
tbl.Rows.Add(row);

i
rdr.CloseO;

! DataSet
. , ,
. ?
, . ADO.NET
DataAdapter.
DataSet DataTable.

DataAdapter
DataAdapter
ADO.NET. DataAdapter
DataSet. , DataAdapter
, DataSet. . DataAdapter
10. DataAdapter.

DataAdapter ,

DataAdapter ,
, Command ADO, rdoQuery
RDO QueryDefDAO. .
DataAdapter , .
DataAdapter
ADO, RDO DAO
. , Command ADO -

5 DataAdapter

135

Recordset, Connection.
. , , ,
- .
DataAdapter . , Fill.
. Fill
DataAdapter, , , ,
DataSet .
DataAdapter DataSet
DataTable DataSet, Fill DataAdapter.
Visual Basic .NET
OleDbDataAdapter.Fill(DataSet)
Visual C# .NET
OleDbDataAdapter.Fill(DataSet);
, - . DataSet
DataAdapter, DataAdapter DataSet. , DataSet
,
. , DataSet
, -
.
DataAdapter
, DataSet
DataAdapter .
DataSet,
.
.
, ADO Recordset,
Command.
Update Recordset. Command .
ADO.NET , DataSet,
Update DataAdapter. DataSet
. DataSet , DataAdapter.

DataAdapter
: DataAdapter
. -, ADO, RDO

136

II

: .NET

ADO ADO.NET. INSERT,


UPDATE DELETE, .
DataAdapter
, : Bay!, *
?.
,
(rapid application development, RAD). .
UPDATE, INSERT INTO DELETE,
DAO, RDO ADO , Recordset rdoRecordset, . ,
Recordset ,
- Visual Studio .NET
, ADO.NET. , : ? : , . , ,
: ?
, , .
, RAD- ,
,
.
DataAdapter.
Command: ,
,
. Command
, , DataSet .
, (, )'
, ). , . DataAdapter . ADO.NET , , ADO DAO. Visual Studio .NET , .
, DataAdapter 10. -

5 DataAdapter

137

DataAdapter , .

DataAdapter
,
DataAdapter,
.
DataAdapter
DataSet DataTable. 4, Command DataReader. DataAdapter
Command , DataAdapter DataSet.
. 5-1 DataAdapter.
DataSet
TabteMappirjgs

IColumnMappings

SelectCommantf

UpdateCommand

insertCommantf

DeleteCommand

. 5-1.

DataAdapter


DataAdapter
DataSet, DataAdapter Command.
DataAdapter DataReader
DataSet. ,
, .
Command, DataAdapter
, SelectCommand DataAdapter.

5-5958

138

II

: .NET

, DataAdapter ,
Command: InsertCommand, UpdateCommand DeleteCommand. DataAdapter Command ,
DataSet. 10.
TabieMappings
DataAdapter , DataReader
DataSet. ,
DataSet . , DataSet
. . ,
Employees EmpID, LNamc FName, EmployeelD, LastName FirstName ;
SELECT EmpID AS EmployeelD,

LName AS LastName, FHame AS FirstName

FROM Employees

DataAdapter , DataSet TabieMappings.



EmpID. LName FName. : ,
123.
Employees DataSet, EmployeelD, LastName FirstName.
TabieMappings DataAdapter
DataSet.
TabieMappings DataTableMappingsCollection, DataTableMapping. DataTableMapping (, ) DataSet. , DataTableMapping
Column-Mappings, DataColumnMappingsCottection, DataColumnMapping.
DataColumnMapping DataSet.
DataCohimnMappings ,
. IntelHSense , Visual Studio .NET
.
. 5-2 , TabieMappings DataAdapter , ,
DataSet.
Table 123 Employees
DataSet, ,
Table Employees. , DataAdapter ,
. DataAdapter
DataReader , .

5 DataAdapter

1 19

, Table, TableMappings Table Employees.

TableMappings DataAdapte

S
^"---^ ..^--""

123

Employees

DataSet
Emptoyees

EmpID EmployeelD

EmployeelD

LName

LName LastName

LastName

FNarne

FPJame FirstName

FirstName

. 5-2.

TableMappings DataAdapter

TableMappings DataAdapter
.
Visual Basic .NET
Dim da As OleDbDataAdapter
' DataAdapter
Dim TblHap As DataTableMapping
Dim ColHap As DataColumnMapping
= da.TableMappings.Add("Table", "Employees")
ColMap = TblHap.ColumnMappings.Add("EmpID", "EmployeelD")
ColMap = TblHap.ColumnMappings,AddC'LName", "LastName")
ColHap = ,ColumnMappings.Add("FName", "FirstName")

Visual C# .NET
OleDbDataAdapter da;
// DataAdapter
DataTableMapoing ;
DataColunnMapping ColMap;
= da.TableMappings,AddC'Table", "Employees");
ColMap = TblHap.ColumnMappings.AddC'EmpID", "EmployeelD");
ColHap = .ColumnMappings.AddC'LName", "LastName");
ColHap = .ColumnMappings.Add("FName", "FirstName");

DataAdapter
, DataAdapter,
, ,

DataAdapter
DataAdapter SelectCommand Command. SelectCommand DataAdapter.

140

II

: .NET

Visual Basic .NET


Dim strConn As String = "Provider=SQLOLEDB; Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
Dim strSQL As String = "SELECT CustomerlD, CompanyName FROM Customers"
Dim cmd As New 01eDbCommand(strSQL, en)
Dim da As New OleDbDataAdapterf)
da.SelectCommand = cmd

Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
string strSQL = "SELECT CustomerlD, CompanyName FROM Customers";
OleDbCommand cmd = new 01eDbCommand(strSQL, en);
OleDbDataAdapter da = new OleDbDataAdapterQ;
da.SelectCommand = cmd;
DataAdapter
DataAdapter ,
DataAdapter. }' .
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local}\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim strSQL As String = "SELECT CustomerlD, CompanyName FROM Customers"
Dim da As New OleDbDataAdapterCstrSQL, strConn)
Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
string strSQL = "SELECT CustomerlD, CompanyName FROM Customers";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);

. , DataAdapter. , DataAdapter
Connection. , DataAdapter Connection, DataAdapter,
Connection.
DataAdapter, Connection-.
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSOK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim on As New OleDbConnection(strConn)
Dim daCustomers, daOrders As OleDbDataAdapter

DataAdapter

141

daCustomers = New OleDbDataAdapterf'SELECT ... FROM Customers", en)


daOrders = New 01eDbDataAdapter("SELECT . . . FROM Orders", en)

Visual C# .NET
string strConn = "ProviOer=SQLOLED<B; Data Source=(local)\\NetSDK;" +
"Initial Catalog==Northwind;Trusted_Connection=Yes;";
QleDbConnection en = new OleDbConnection(strConn);
OleDbDataAdapter daCustomers, daOrders;
daCustomers = new 01eDbDataAdapter("SELECT . . . FROM Customers", en);
daOrders = new 01eDbDataAdapter("SELECT ... FROM Orders", en);

DataAdapter Command.
, DataAdapter
DataSet, :
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB; Data Source=(local)\NetSDK; " &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New 01eDbConnectlon{strConn)
Dim strSQL As String = "SELECT CustomerlD, CompanyName FROM Customers"
Dim cmd As New GleDbCommand(strSQL, en)
Dim da As New OleDbDataAdapter(cmd)

Visual C# .NET
string strConn = "Provider=SQLOLEDB; Data .Source=(local)\\NetSDK;"
"Initial Catalog=Northwind;Trusted_Connection;";
OleDbConnection en = new OleDbConnection(strConn);
string strSOL = "SELECT CustomerlD, CompanyName FROM Customers"
QleDbCommand cmd = new 01eDbCommand(strSQL, en);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);


DataAdapter ,
, DataSet. DataAdapter, Customers Northwind.
Fill
Fill DataAdapter ,
SelectCommand DataAdapter,
DataSet. Fill.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone " & _

142

: .NET

"FROM Customers"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New DataSetQ
da.Fill(ds)
Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT CustomerlD, CompanyName, ContactNante, Phone " +
"FROM Customers";
OleDbDataAdapter da = new 01eObDataAdapter(strSQL, strConn);
DataSet ds = new DataSetO;
da.FillCds);
Fill DataSet
DataTable. , , , CustomerlD, CompanyName, ContactName Phone.
DataTable DataColumn Fill
Fill DataSet
DataTable. CustomerlD, CompanyName, ContactName Phone, Customers, a Table.
TableMappings
DataAdapter.
DataAdapter, DataTable Customer:
Visual Basic .NET
'
' ,
Dim da As New QleDbDataAdapter(strSQL, strConn)
da.TableMappings.Add("Table", "Customers")
Dim ds As New DataSetO
da.Fill(ds)
Visual C# .NET
//
// ,
OleDbDataAdapter da = new 01eObDataAdapter(strSQL, strConn);
da.TableMappings.Add("Table", "Customers");
DataSet ds = new DataSetO;
da.Fill(ds);
TableMappings .

DataAdapter

143

Fill
DataSet Fill
DataAdapter, .
DataTable
DataAdapter Fill,
DataTable.
TableMappings DataAdapter.
Fill.
DataAdapter.Fill{DataSet, "")
DataSet Fill, TableMappings.
, DataSet DataTable:
DataAdapter.Fill(DataTable)
, DataTable.
Fill DataAdapter
,
, , 20 . DataAdapter
Fill, :
DataAdapter.Fill(DataSet, intStartRecord, intNumRecorbs, "")
, 0. ,
;
DataAdapter. FllHDataSet, O, 20, "Products")
, Fill DataSet. ,
1000 20 .
DataAdapter.Fill(DataSet, 980, 20, "Products")
20 , , DataSet.
1000 . DataAdapter 49 .
, Fill ,
. { ) DataSet Data-Reader 14, Web-.
DataSet
Recordset DataAdapter
OLE DB .NET Fill, Recordset ADO DataSet ADO.NET

144

II

: .NET

OleDbDataAdapter.Fill(DataSet, AdoRecordset, "TableName")


OleDbDataAdapter.Fill(DataTable, AdoRecordset)
, .NET
, Recordset ADO.

, , Fill, , DataAdapter
Command Connection. 4
Execute Command
Connection. Command . DataAdapter .
Fill DataAdapter Connection,
SelectCommand, , DataAdapter , , Connection. ,
DataAdapter . Connection, SelectCommand, . Connection Fill, .
DataAdapter Connection , . , .
, DataAdapter DataSet .
, DataSet , :
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB; Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
Dim daCustomers, daOrders As OleDbDataAdapter
daCustomers = New 01eDbDataAdapter("SELECT ... FROM Customers", en)
daOrders = New 01eDbDataAdapter("SELECT ... FROM Orders", en)
Dim ds As New DataSetO
daCustomers.Fill(ds)
daOrders.Fill(ds)

Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
OleDbDataAdapter daCustomers, daOrders;
daCustomers = new OleDbDataAdapterC'SELECT ... FROM Customers", en);
daOrders = new OleDbDataAdapterC'SELECT ... FROK Orders", en);
ds = new DataSetO;

5 DataAdapter

145

daCustomers.Fill(ds);
daOrders.Fill<ds);
DataAdapterFill Connection. ,
Fill DataAdapter Open Connection. ,
Call:
.
daCustomers.Fill(ds)
daOrders.Fill(ds)
cn.CloseO

Fill
, DataSet? ,
DataAdapter
. DataSet ( DataTable)
Fill DataAdapter.
Fill
DataAdapter^
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local}\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone " & _
"FROM Customers"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New DataSet()
da.Fill(ds, "Customers")
da.Fill(ds, "Customers")

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;"
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone " +
"FROM Customers";
OleDbDataAdapter da = new 01eDbuataAdapter(strSQL, strConn);
DataSet ds = new DataSet();
da.Fill(ds, "Customers");
da.Fill(ds, "Customers");
Fill, DataAdapter DataSet.

146

II

: .NET

Fill DataSet Customers.


Fill DataSet,
, DataSet .
DataAdapter ,
. . . DataTable
PrimatyKey. DataAdapter DataTable
, DataAdapter .
PrimatyKey DataTable
, 6,
,
. DataAdapterfill Customers DataSet ,
DataAdapter .
, , |} .
Fill . DataAdapter
DataTable , . , , DataAdapter DataTable . DataTable .
, DataAdapterFill , , DataAdapter DataTable. - . DataAdapter,
, , ,
DataTable.
. , DataSet DataTable Fill DataAdapter. (
), DataSet , .

DataSet
TableMappings DataAdapter. . .
TableMappings DataAdapter
TableMappings , DataAdapter DataSet
. TableMappings DataAdapter
Fill, DataSet
, DataAdapter , DataTable Table.
TableMappings DataTableMappingCollection, DataTableMapping.
TableMappings DataTableMapping, DataAdapter, DataTable Employees:

DataAdapter

DataAdapter.TableHapplngs.AddC'Table",

147

"Employees")

DataTableMappings,
.
EmpID, LName FName EmployeelD, LastName
FirstName DataSet:
Visual Basic .NET
Dim da As OleObDataAdapter
' DataAdapter
Dim TblMap As DataTableMapping
Dim ColMap As DataColumnMapping
= da.TableMappings.Add("Table", "Employees")
ColMap = TblMap.ColumnMappings.Add("EmpID", "EmployeelD")
ColMap = ,ColumnMappings.AddC'LName", "LastName")
ColMap = TblMap,ColumnMappings.Add("FName", "FirstName")

Visual C# .NET
OleDbDataAdapter da;
// DataAdapter
DataTableMapping TblMap;
DataColumnMapping ColMap;
TblMap = da.TableMappings.Add("Table", "Employees");
ColMap = TblMap.ColumnMappings.Add("EmpID", "EmployeelD");
ColMap = TblMap.ColumnMappings.AddC'lName", "LastName");
ColMap = TblMap.ColumnMappings.AddC'FName", "FirstName");

DataTableMappingCollection DataColwnnMappingCollection Top,AddRange,


:
Visual Basic .NET
Dim da As New OleDbDataAdapterQ
' DataAdapter
Dim TblMap As DataTableMapping
Dim ColMapArray As DataColumnMappingO
= da.TableHappings.AddC'Table", "Employees")
ColMapArray = New DataColumnMappingO _
{New DataColumnMappingC'EmpID", "EmployeelD"), _
New DataColumnNappingC'LName", "LastName"), _
New DataColunrnMapping("FName", "FirstName")}
TblMap.ColumnMappings.AddRangeCColMapArray)
Visual C# .NET
OleDbOataAdapter da = new 01eDbDataAdapter();
// DataAdapter
DataTableMapping TblMap;
DataColumnMapping[] ColMapArray;
TblMap = da.TableMappings.AddC'Table", "Employees");

148

II

: .NET

ColMapArray = new DataColumnMappingE]


{new DataColumnMappingC'EmpID", "EmployeelD"),
new DataColumnMapping("LNane", "LastName"),
new DataColumnMappingC'FName", "FirstName")};
TblMap.ColumnMappings.AddRange(ColMapArray);

MissingMappingAction
, TableMappings DataTable . , , , ,
. DataAdapterfi.il DataTable
, DataAdapter .
DataSet
, . ADO.NET , ,
DataSet TableMappings DataAdapter DataSet.
DataAdapter , TableMappings, MissingMappingAction
, .
MissingMappingAction , SystemData.
Passthrough. DataAdapter , TableMappings,
DataSet. MissingMappingAction
Ignore, DataAdapter , TableMappings.
, MissingMappingAction Error, DataAdapter, TableMappings
, .


. , Microsoft SQL Server, , :
SELECT CustomerlD, CompanyName, ContactName, Phone
FROM Customers WHERE CustomerlD = 'ALFKI 1 ;
SELECT OrderlD, CustomerlD, EmployeelD, OrderDate
FROM Orders WHERE CustomerlD = 'ALFKI'

DataAdapter, ,
DataSet
DataAdapte.Fill(DataSet)
DataTable, DataSet. , Customers,
DataTable Table, ,

DataAdapter

149

Orders, DataTable Table 1. ,


DataTable .
TableMappings DataAdapter DataTableMapping. ,
, DataAdapter . DataSet Customers Orders.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusteci_Connection=Yes;"
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone " & _
"FROM Customers WHERE CustomerlD = 'ALFKI'; " & _
"SELECT OrderlD, CustomerlD, EmployeelD, OrderDate " & _
"FROM Orders WHERE CustomerlD = 'ALFKI1"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
da, TableMappings.Add("Table", "Customers")
da. TableMappings.Add("Table1", "Orders")
Dim ds As New DataSetQ
da.Fill(ds)

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone " +
"FROM Customers WHERE CustomerlD = 'ALFKI'; " +
"SELECT OrderlD, CustomerlD, EmployeelD, OrderDate " +
"FROM Orders WHERE CustomerlD = 'ALFKI'";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
da.TableMappings.Add("Table", "Customers");
da.TableMappings.Add("Table1", "Orders");
DataSet ds = new DataSetO;
da.Fill(ds);


DataAdapter , , DataSet DataTable. , :
CREATE PROCEDURE GetAllCustomers AS
SELECT CustomerlD, CompanyName, ContactName, Phone FROM Customers
RETURN


DataSet:

150

II ; .NET

{CALL GetAllCustomers}


EXEC GetAllCustomers

, DataAdapter Command,
CommandType StoredProcedure.
Command, CommandType
, 4.
.
Oracle
SQL Server, Oracle .
Microsoft OLE DB Provider for Oracle Microsoft ODBC Driver
for Oracle Oracle . Microsoft. Oracle
:
(CALL PackageName.ProcName (?, {resultset 20, OutParaml,
OutParam2, ... })}


DataTable,
, ,
(, PRIMARY KEY, NULL). , DataAdapter
.
, DataAdapter
MissingSchemaAction FillSchema (, ,
).
MissingSchemaAction
, , , DataAdapter fill DataSet DataTable, . DataAdapter
DataSet DataTable . DataAdapter
MissingSchemaAction.
MissingSchemaAction , SystemData.
Add. MissingMappingAction,
MissingSchemaAction Ignore . , Error, DataA. , .

5 DataAdapter

151

MissingSchemaAction , AddWitbKey,
. MissingSchemaAction DataAdapter, ,
DataSet DataTable , : MaxLengtb AHowDbNull. DataTable , MissingSchemaAction DataAdapter
,
FHISchema
DataAdapter FHISchema,
DataSet DataTable . FHISchema
Fill. FillSchema
DataSet, DataTable DataSet .
FHISchema ScbemaType,
Mapped Source. ,
DataAdapter TableMappings . FillSchema
ScbemaType Source, DataAdapter , . Mapped DataAdapter TableMappings.

, FiJISchema Autolncrement, Allou-DBNull MaxLengtb DataTable ,

DataAdapter
Visual Studio .NET
, DataAdapter, , Visual Studio .NET
,

DataAdapter
Data Visual Studio .NET OleDbDataAdapter SqlDataAdapter. (. 5-3),
DataAdapter. , Data Adapter Configuration Wizard.

Data Adapter Configuration Wizard


Data Adapter Configuration Wizard Visual Studio .NET DataAdapter - .
,
. (. 5-4) Choose Connection
Data Form Wizard: -

II : .NET

152

^ Wn>duvra*|iplir4tion1

Edit

Mirrisafi v,iwl [

lefm1.vb|[Jeiignl

Bow ftojKt

. 5-3.

DataAdapter

. OleDbDataAdapter, Server Explorer .


SqlDataAdapter , OLE
DB- SQL Server. Next,
.
iSi**t* Adapter ConfieiHatidn Wizard
Choose Your Data Connection
The dats Uptti * execute queries usng this connection to load
:

.1.

ectlon ihuuU Che data adapter me?

. 5-4.

DataAdapter

SQL- (, SELECT CustomerlD, CompanyName FROM Customers) . Data Adapter Configuration Wizard . SQL-. -

5 DataAdapter

153

DataAdapter 10, . Use SQL Statements (. 5-5) Nest.

d*a adopttr the databa

[reMe new >lwed procedur

'* Uu e_Kjsting stared procedures

. 5-5-

DataAdapter


(, 5-6). , . 10.
HBata AOrtplci Configuration Wiraid
Generate the 5. statements
Delete statements.
TV(J6myw*S3.5(4MtitatM(4Iilr* QuHrBA Hi grJcWrslv dKV the Qti

hat dala hailM [he data adapter bad mta (M dataset'

. 5-6.

Query Builder, Query Builder, ,


Microsoft Access. Query Builder , ,
DataAdapter. Query
Builder (. 5-7) ,
.
Query Builder , ,
. -

154

II

: .NET

Run.
. 5-8 Query Builder. , .
. SQL , .
.

. 5-7.

Add Table Query Builder

Rattlesnake Canyo Paula


Old Wc"ld Prtcates
5ave-a-lot Maiketi
The CiKker Box
huig.f Cwote Ilii
Great lal FcM t
TraTi Head Gaum
Sent R9- a All

. 5-8.

Rene Pht(n
Jc*e Pavsrott:
Liu Wtng
YosH Latimer
toward 5nydei
Helvetlus
Ait arinschwei(

FUtt-

' .

use
. -

!'

Krtfand

. . ,

USA

Query Builder

DataAdapter

155

, . Query Builder , Data Adapter Configuration Wizard.


Next, DataAdapter. . 5-9 Data Adapter Configuration Wizard

Dels*:
f GFavasd sEiEC'
* Generrted table
* Gnnaralcd TER3 tiacemert.
' Gtaersea UPDSTE .

. 5-9. Data Adapter Configuration Wizard


DataAdapter,
, , . ,
, ,
DataAdapter.
DataAdapter ,
Properties
(. 5-10). CommandText Command, SelectCommand DataAdapter.
Data Adapter Configuration Wziard
DataAdapter, DataAdapter , Configure Data Adapter Properties.

Server Explorer
DataAdapter , Server Explorer . , ,
DataAdapter .
, DataAdapter , .
, Server Explorer,
, ,
DataAdapter, Server Explorer

156

II

. 5-.

: .NET

DataAdapter

(. 5-11). , Ctrl.

. 5-11.

DataAdapter

5 DataAdapter

157

,
DataAdapter
Query Builder . . , ( ,
- ,
Red Sox); , .
, .
, , . Query Builder ,
, DataAdapter.

DataAdapter, Properties Preview Data. , Data Adapter Preview (. 5-12). DataAdapter , Fill Dataset.

ly
RatUwMtvC Paula'Ati-

utouquerque

OH World Onl RoiePhltcs


Save-a-lDtMa .'osePaviiolli Boi
TheCrackct

Wong

HUTHTY coYt* rosTi Lamer

Bull!
Elgin

GHEAL
IRA1H
SPIIB

Split Kail Bee. *rt Braunazn

Lander

LONEP

IcnesomePri FranWfcnn

Portland

,EBI

"LETSS

WHITC
WZVK

The Big Chee Liz Nixon

Portland

Let's Stop N 5 Jaime Yor-ei

San Frsn

While Clover

Karl Jabloi*] Seattle


John Steel

WalaWaH

. 5-12. ,
DataAdapter

,
.
, ,
, ADO.NET. , DataAdapter, Command Parameter, Data Adapter Configuration Wizard ,
.

158

II : .NET

InitializeComponent , ,
.

DataAdapter
DataAdapter , .
.

DataAdapter
DataAdapter
DataSet.
SelectCommand, UpdateCommand, InsertCommand
DeleteCommand, Command, DataAdapter DataSet,
DataSet DataSet
. . 5-1 DataAdapter.
5-1.

OleDbDataAdapter

AcceptChangesDuringFill

ContinueL'pdateOnError

Boolean

DeleteCommand

OleDbCommand

InsertCommand

OleDbCommand

Boolean

MissingMappingAction

MissingMappingAction

MissingScbemaAction

MissingSchemaAction

SelectCommand

OleDbCommand

TableMappings

DataTableMappingCollection

UpdaleCommand

OleDbCommand


RowState ,
DataAdapter (
True)
,
DataAdapter
( False)



DataAdapter ,
TableMappings ( Passthrougb)

DataAdapter ,
Columns DataTable ( Add)

DataSet DataTable
,
DataAdapter DataSet

5 DataAdapter

159

Selectcommand, UpdateCommand, InsertCommand DeleteCommand


DataAdapter Command. .NET. , Selectcommand OleDbDataAdapter QleDbCommand,
SqlDataAdapter SqlCommand ( Command 4).
DataAdapter , CommandText Command, Selectcommand
. DataAdapter. Command, ADO.NET
SelectCommand DataAdapter.
DataAdapter Connection,
Command, SelectCommand
DataAdapter. , DataAdap'er
Connection, ConnectionString
Connection
Command, SelectCommand DataAdapter.
TableMappings
, DataAdapter DataSet
ADO.NET. DataAdapter
DataSet? , Update OleDbDataAdapter SqlDataAdapter
DataSet. ,
DataTable? DataAdapter , DataTable
?
DataAdapter TableMappings,
DataTableMappings. DataTableMappings ColumnMappings, DataColumnMappings. DataTable DataColumn DataSet.
, DataAdapter
TableMappings , DataSet
. ,
SELECT Customer-ID, CompanyName, ContactName, Phone FROM Customers

DataTable Customers, DataColumn,


. DataTable DataColumn , TableMappings DataAdapter.
TableMappings DataAdapter,
. TableMapping ColwnnMapping
, DataAdapter ,
DataSet.
Visual Basic .NET
Dim strSQL, strConn As String
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone FROM Customers"

160

II

: .NET

strConn = "Provider=SQU)LEDB;Data Source=(local)\NetSDK;" & _


"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
With da.TableMappings.Add("Table", "Customers").ColumnMappings
.Add("CustomerlD", "CustomerlD")
.Add("CompanyName", "CompanyName")
.AddC'ContactName", "ContactName")
.Add("Phone", "Phone")
End With

Visual C# .NET
string strSQL, strConn;
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone FROM Customers";
strConn = "Provider=SQ1.0LEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
da.TableHappings.Add{"Table", "Customers");
DataColumnMappingCollection cm = da.TableHappings[0].ColumnHappings;
cm.Add("CustomerlD", "CustomerlD");
cm.Add("CompanyName", "CompanyName");
cm.Add("ContactName", "ContactName"};
cm.Add("Phone", "Phone");

AddRange DataTableMappingCoUection DataColumnfrlappingCollection


:
Visual Basic .NET
Dim cm As CommonDataColumnMapping = da.TableMappings(0).ColumnMappings
cm.AddRange(New Common.DataColumnHappingO
{New Common.DataColumnMapplngC"CustomerlD", "CustomerlD"),' _
New Common.DataColumnMappingf"CompanyName", "CompanyName"), _
New Common.DataColumnMapping("ContactName", "ContactName"), _
New Common.DataColumnHapping("Phone", "Phone")})
Visual C# .NET
DataColumnMappingCollection cm = da.TableMappings[0].ColumnMappings;
cm.AddRange(new DataColumnMapping[]
{new DataColumnMapping("CustomerlD", "CustomerlD"),
new DataColumnHappingC"CompanyName", "CompanyName"),
new DataColumnMapping("ContactName", "ContactName"),
new DataColumnMappingC'Phone", "Phone")});

, DataAdapter
DataSet, TableMappings?
DataAdapter , . :

DataAdapter

161

Visual Basic .NET


Dim strSQL, strConn As String
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone FROM Customers"
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New DataSet
da.Fill(ds)
Console.WriteLine(ds.Tables("Table").Rows(0)("CustomerID").ToString)

Visual C# .NET
string strSQL, gtrConn;
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone FROM Customers";
strConn = "Provider=SQLOLEDB;Data !3ource=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbDataAdapter da = new 01eDbOataAdapter(strSQL, strConn);
DataSet ds = new DataSet;
da.Fill(ds);
Console.WriteLine(ds.Tables["Table"].Rows[0]["CustomerID"].ToString());
MissingMappingAction MissingSchemaAction
: TableMappings DataAdapter.
DataSet;
DataAdapter.
, DataAdapter TableMappings . MissingMappingAction
, DataAdapter , TableMappings. Passtbrough; MissingMappingAction, SystemJData.
MissingMappingAction Ignore, DataAdapter , TableMappings. , MissingMappingAction Error, DataAdapter, TableMappings , .
DataAdapter MissingSchemaAction, , ,
DataSet. Add; DataAdapter
DataSet. MissingSchemAction , SystemData AddWithKey,
Ignores Error. MissingSchemaAction Ignore, DataAdapter
, DataSet.
Error DataAdapter, DataSet ,
.
MissingSchemaAction AddWithKey, DataAdapter
DataSet ,

162

: .NET

. FillSchema DataAdapter, .
AcceptChangesDuringFill
ADO,
, ADO . , Recordset Update, , ADO
. ADO .
ADO.NET , , .
DataAdapter AcceptChangesDuringFill,
. , True.
RowState , DataAdapter.
AcceptChangesDttringFul True, RowState
, DataAdapter, Unchanged. False
RowState DataRow New.
, , AcceptCfoangesDuringFill False, , DataSet
DataAdapter, ,
.
ContinueUpdateOnError
DataAdapter .
, DataSet
DataAdapter, ,
. : 10 11. , , .
ContinueUpdateOnError DataAdapter , DataRow. False, . .
DataAdapter . ,
DataAdapter DataRow, ContinueUpdateOnError True.
, DataAdapter ? , DataSet .
*. , , , . ,
.

5 DataAdapter

163

DataAdapter
. 5-2 , DataAdapter.
5-2.

QteDbDataAdapter

Fill
FillSchetna
GetFillParameters
Update

SelectCommand DataTable
,
SelectCommand
SelectCommand
, DataSet {DataTable
DataRows}

Fill
DataAdapterfill ,
SelectCommand, DataTable
DataSet. , Fill 32-
integer, , DataAdapter,
, Fill:
Visual Basic .NET
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New DataSetO
Dim intRowsRetrieved As Integer = ba.Fill(ds)
Visual C# .NET
OleDbDataAdapter da = new OleDbDataAdapterfstrSQL, strConn);
DataSet ds = new DataSetO;
int intRowsRetrieved = da.Fill(ds);
DataAdapter TableMappings
, DataTable DataColumn
DataSet . TableMappings DataSet , DataAdapter MissingMappingAction MissingSchemaAction , .
Fill DataAdapter . DataSet DataTable. DataSet DataTable,
:

Visual Basic .NET


Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New DataSetO
Dim intRowsRetrieved As Integer
intRowsRetrieved = da.Flll(ds, "Customers")

164

It

: .NET

intRowsRetrieved = da. Fill(ds.Tables("Customers"))


intRowsRetrieved = da.Fill(ds, 11, 10, "Customers")

Visual C# .NET
DleDbDataAdapter da = new 01eDbDataAdapter{strSQL, strConn);
DataSet ds = new DataSetQ;
int intRowsRetrieved;
intRowsRetrieved = da.Fillfds, "Customers");
intRowsRetrieved = da.Fill(ds.Tables["Customers"]};
intRowsRetrieved = da.Fill(ds, 11, 10, "Customers");

, DataAdapter Fill, Web-, . , , 10 . , Fill DataAdapter:


Visual Basic .NET
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New OataSetO
Dim intStartingRow As Integer = 10
Dim intRowsToRetrieve As Integer = 10
Dim intRowsRetrieved As Integer
intRowsRetrieved = da.Fill(ds, intStartingRow,
intRowsToRetrieve, "Customers")
Visual C# .NET
OleDbDataAdapter da = new 01eDbDataAdapter{strSQL, strConn);
DataSet ds = new DataSetO;
int intStartingRow = 10;
int intRowsToRetrieve = 10;
int intRowsRetrieved = da.Fill(ds, intStartingRow,
intRowsToRetrieve, "Customers");

DataAdapter , ,
( ), DataAdapter 10 .
( ) , DataAdapter ,
.
?
. , 100
10 10 . ,
10 . , 10 10 . : ,
20 . 100 -

DataAdapter

165

, DataAdapter 90. , . DataAdapter


? , .
,
, 10 :
SELECT TOP 10 Customer-ID, CompanyName, ContactName, Phone
FROM Customers ORDER BY CustomerlD

CustomerlD BSBEV,
11 20:
SELECT TOP 10 CustomerlD, CompanyName, ContactName, Phone
FROM Customers ORDER BY CustomerlD
WHERE CustomerlD > "BSBEV"

,
.

; , .
OleDbDataAdapter Fill,
ADO-. Recordset ADO
DataSet ADO.NET; , DataSet,
Recordset DataTable Recordset. :
Visual Basic .NET
Dim rs As New ADODB.HecordsetC)
rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient
rs.Open(strSQL, strConn)
Dim da As New OleDbDataAdapterO
Dim ds As New DataSetf)
Dim intRowsRetrieved As Integer
intRowsRetrieved = da.Fill(ds, rs, "Customers")
intRowsRetrieved = da. Fill(ds.Tables("Customers"), rs)

Visual C# .NET
Recordset rs = new RecordsetClassf);
rs.CursorLocation = CursorLocationEnum.adUseClient;
rs.Open(strSQL, strConn, CursorTypeEnum.adOpenStatic,
LockTypeEnum.adLockReadOnly, (int) CommandTypeEnum.adCmdText);
OleDbDataAdapter da = new OleDbDataAdapterO;
OataSet ds = new DataSetO;
int intRowsRetrieved;
intRowsRetrieved = da.Fill(ds, rs, "Customers");
intRowsRetrieved = da.Fill(ds.Tables["Customers"], rs);

166

II : .NET

DataAdapter Recordset ADO


DataSet ADO.NET, .

FillSchema
FillSchema
. Fill, FillScbema . , FillSchema Null AllowDBNull DataColumn.
, , FillScbema
DataTable . , , , .
FillSchema DataAdapter
, . , DataAdapter .
( ), DataAdapter
, ( ). , DataAdapter
DataTable. DataTable .
FillSchema Fill . Fill, FillSchema
DataSet, DataSet DataTable. ,
FillSchema . ,
, DataAdapter,
TableMappings.
SchemaType
SystemData Source Mapped. Source, DataAdapter , . Mapped DataAdapter TableMappings ,
Fill. FillScbema:
Visual Basic .NET
Dim da As New 01eDuDataAdapter(strSQL, strConn)
Dim ds As New Data8et()
' DataSet SchemaType.
da,FillSchema(ds, SchemaType.Source)
' DataSet, SchemaType
da.FillSchema(ds, SchemaType.Source, "Table")
Dim tbl As New DataTablaO
' DataTable SchemaType.
da.FlllSchema(tbl, SchemaType.Source)

DataAdapter

167

Visual C# .NET
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
DataSet ds = new DataSetQ;
// DataSet SchemaType
da.FillSchema(ds, SchemaType.Source);
// DataSet, SchemaType
da.FillSchemaCds, SchemaType.Sou , "TableName");
DataTable tbl = new DataTableO;
// DataTable SchemaType
da.FillSchema(tbl, SchemaType.Source);

FillSchema DataTabie,
FillSchema, DataTable. DataAdapter
DataTable, .
GetFillParameters
GetFillParameters Parameters SelectCommand DataAdapter, . GetFillParameters /Parameter, Parameter , .NET (, OleDbParameter SqlParametef),
Size, Precision Scale
, GetFillParameters:
Visual Basic .NET
Dim strSQL As String = "SELECT CustomerlD, CompanyName " &
"FROM Customers WHERE CustomerlD LIKE ?"
da = New 01eDbDataAdapter(strSQL, strConn)
da.SelectCommand.Parameters.Append("@CustomerID", _
OleDbType.VarWChar, 5)
da.GetFillParameters(O).Value = "ALFKI"
Visual C# .NET
string strSQL = "SELECT CustomerlD, CompanyName FROM Customers " +
"WHERE CustomerlD LIKE ?";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
da.SelectCommand.Parameters.Append("CustomerlD", OleDbType.VarWChar,
da.GetFillParameters[0].Value = "ALFKI";

5);

Command Parameter 4.

Update
Update ,
DataTable DataSet,

168

II : .NET

Fill FillSchema, Update DataSet,


DataSet DataTable. Update
, DataRoiv. ,
, .
Update integer, , .
, Update
10.
Visual Basic .NET
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim intChangesSubmitted As Integer
intChangesSubmitted = da.Update(ds)
intChangesSubmitted = da.Update(ds, "TableName")
intChangesSubmitted = da.Update(ds.Tables("TableName"))
Dim aflowsf) As Dataflow
intChangesSubmitted = da.Update(aRows)
Visual C# .NET
OleDbDataAdapter da;
DataSet ds;
irtt
intChangesSubmitted;
intChangesSubmitted = da.Update(ds);
intChangesSubmitted = da.Update(ds, "TableName"};
intChangesSubmitted = da.Update(ds.Tables["TableName"]);
DataRow[] aRows;
intChangesSubmitted = da.Update(aRows);

DataAdapter
. 5-3 , DataAdapter.
5-3.

'
RoivUpdating
RowUpdated

OleDbDataAdapter

, DataSet DataTable
DataAdapter -

FillError
DataSet DataTable DataAdapter
, FillError.

DataAdapter

169

Visual Basic .NET


Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT TOP 1 OrderlD, CustomerlD, EmployeelO FROM Orders"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
da.MissingSchemaAction = MissingSchemaAction. Error
AddHandler da.FillError, AddressOf da_FillError
Dim tbl As New DataTable("Orders")
tbl.Columns.Add("OrderlD", GetType(Integer))
tbl.Columns.Add("CustomerlD", GetType(String))
da.Fill(tbl)
Public Sub da_FillError(ByVal sender As Object,
ByVal e As FillErrorEventArgs)
Console.WriteLine(e.Errors.Message)
e.Continue = True
End Sub

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSOL = "SELECT TOP 1 OrderlD, CustomerlD, EmployeelD FROM Orders";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
da,MissingSchemaAction = MissingSchemaAction.Error;
da.FillError += new FillErrorEventHandler(da_FillError);
DataTable tbl = new DataTableC'Orders");
tbl.Columns.Add("OrderlD", typeof(int));
tbl.Columns.Add("CustomerID", typeof(st ring));
da.Fill(tbl);
static void da_FillError(object sender, FillErrorEventArgs e)

{
Console,WriteLine(e.Errors.Message);
e.Continue = true;

}
, FillError , , DataAdapter DataSet DataTable.
RowUpdating RowUpdated
DataAdapter
DataAdapter.Update.
, , RowUpdating. , RowUpdatea.
, .

7-5958

1 70

II : .NET

Visual Basic .NET


Dint strConn, strSQL As String
strConn = "Provider=SQLOLEOB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT TOP 1 OrderlD, CustomerlD, EmployeelD FROM Orders"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
AddHandler da.RowUpdated, AddressOf da_RowUpdated
AddHandler da.RowUpdating, AddressOf da_RowUpdating
Dim tbl As New DataTablef'Orders")
da.Fill(tbl)
tbl.Rows(0)("EmployeeID") = CInt(tbl.Rows(0)("EmployeeID")) + 1
Dim cb As New OleDbCommandBuilder(da)
da.Update(tbl)
tbl.Rows(0)("EmployeeID") = CInt(tbl.Rows(0)("EmployeeID")) - 1
da.Update(tbl)
Public Sub da_RowL)pdating(ByVal sender As Object,
ByVal e As OleDbRowUpdatingEventArgs)
Console.WriteLine("RowUpdating Event: " & e.StatementType.ToString)
Console.WriteLine(vbTab & "OrderlD = " & e.Row{"OrderID")>
Console.WriteLinefvbTab & "EmployeelD from: " &
e.Row{"EfnplcyeeID", DataRowVersion.Original
Console.WriteLine(vbTab & "EmployeelD to : " & e.Row("EmployeeID"))
Console.WriteLineO
End Sub
Public Sub da_RowUpdated(ByVal sender As Object,
ByVal e As OleDbRowUpdatedEventArgs)
Console.WriteLineC"RowUpdated Event: " & e.StatementType.ToString)
Console.WriteLine(vbTab & "OrderlD = " & e.Row("OrderID"))
If e.Status = UpdateStatus.ErrorsOccurred Then
Console.WriteLine(vbTab & "Errors occurred")
Else
Console.WriteLine(vbTab & "Success!")
End If
Console.WriteLineO
End Sub

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
StrSQL = "SELECT TOP 1 OrderlD, CustomerlD, EmployeelD FROM Orders";
OleDbDataAdapter da = new OleDbDataAdapterfstrSQL, strConn);
da.RowUpdated += new 01eDbRowUpdatedEventHandler(da_RowUpdated);
da.RowUpdating += new 01eDbflowUpdatingEventHandler(da_Rowllpdating);
DataTable tbl = new DataTable("Orders");
da.Fill(tbl);
tbl.Rows[0]["EmployeeID"] = (int) tbl.Rows[0]["EmployeeID"] + 1;

DataAdapter

171

OleDbCommandBuilder cb = new OleDbCommandBuilder(da);


da.Update(tbl);
tbl.Rows[0]["EmployeeID"] = (int) tbl.Rows[0]["EmployeeID"] - 1;
da.Update(tbl);
static void da_RowUpdating(object sender, OleDbRowUpdatingEventArgs e)
{
Console. WriteLine("RowUpdating Event: " + e.StateraentType.ToStringO);
Console, WriteLine( "\tOrderID = " + e.Row["OrderID"]);
Console. WriteLine("\tEmployeeID from: " +
e. Row["EmployeeID", OataRowVersion. Original]);
Console. WriteLine("\tEmployeeID to : " + e.Row["EmployeeID"]);
Console. WriteLineC);
static void da_RowUpdated(object sender, OleDbRowUpdatedEventArgs e)
{

Console. WriteLineC "RowUpdated Event: " + e.StatementType.ToStringO);


Console. WriteLine<"\tOrderID = " + e.Row["OrderID"]);
if (e. Status == UpdateStatus. ErrorsOccurred)
Console. WriteLine{ "\tErrors red" ) ;
else
Console. Writ eLine{ "\tSuccess! ");
Console. WriteLineC ) ;

,
. DataTable, -, :
DataTable
DataAdapter,
DataTable DataAdaplterfill,
DataTable DataAdapterFillSchemat
. .
, DataTable 20
, FillSchema DataAdapter.
. , DataTable , , , .
?
. . , DataTable . DataTable, ADO. NET
. , ,
PRIMARY KEY UNIQUE, , ADO.NET
DataTable ,

172

II

: .NET

. , DataTable .
, DataTable .
, , ,
DataTable. . -
, DataTable , , DataAdapterf'ilP.
DataTable ',
DataAdapterfill .
ADO.NET
. DataSet EnforceConstraints, True. , ADO.NET
DataSet. Fill DataAdapter False, , True:
Visual Basic .NET
ds.EnforceConstraints = False
dat. FilKds.Tables("Tablel"))
da2.Fill(ds.Tables("Table2"))
ds.EnforceConstraints = True
Visual C# .NET
ds.EnforceConstraints = false;
da1.Fill(ds.Tables["Tablel"]);
da2.Fill(ds.Tables["Table2"]);
ds.EnforceConstraints = true;
Fill , ,
DataTable - .


:
DATASET
ADO.NET

6
DataSet

11
ADO.NET, .NET,
,
ADO.NET , ,
. DataSet, , DataSet

DataSet
, DataSet . , , , Microsoft Excel. DataSet ,
Excel, .
ADO.NET DataReader. ?
4, DataReader , . DataReader , . DataReader , 1
- .
DataSet . .

6 DataSet

175


DataSet . DataSet DataAdapter, DataSet .
DataSet .
, DataSet, .
, . .
DataSet,
.
DataSet
. -, , -
.
DataSet .
. , , , DataSet (
Microsoft .NET Framework) XML-.

, ,
DataSet
. ,
. , DataSet , (,
). , , - .
DataSet ,
DataSet . ,
DataSet ,
, . 8,


DataSet \
. 2 Data Form Wizard
Microsoft Windows, Customers Orders. , , , , .
DataSet
. Data Form Wizard DataGrid, ( DataRelation
).

1 76

111

: DataSet ADO.NET


, , .
.
}' ,
, .
' DataSet DataAdapter. , DataSet ,
(, ),
.
, DataSet.
DataAdapter 10 11.

XML
DataSet ADO.NET XML. DataSet XML-. ,
DataSet ( ,
) XML-,
ADO.NET DataSet XML- .
.
,
. XML- DataSet, XML, XML-, DataSet.
XML- DataSet 12.


, ADO, , ,
Recordset DataSet. , Recordset
, , .
Recordset ,
.
, Recordset
Connection ADO, Recordset . Recordset Supports, , , . Recordset? , Recordset ? Recordset ?
?
, Recordset
, , Recordset .
ADO , , ^' Recordset.

DataSet

177

DataSet ADO.NET , . , ADO.NET-


RecordsCount Recordset -!?>
The rowset is not bookmarkable?.

DataSet
DataSet -
. DataSet DataTable DataRelation.
DataTable DataRow, DataColumn Constraint.
, DataSet.
.

DataSet
DataSet New . DataSet
, DataSetName
.

Visual Basic .NET


Dim ds As New DataSetC'DataSetName")
Console.WriteLine(ds.DataSetName)
Visual C# .NET
DataSet ds = new DataSetC'DataSetName");
Console.WriteLine(ds.DataSetName);

DataSet , DataSet, DataTable, DataColumn, DataRow, Constraint DataRelation


SystemData,

,
Data Adapter.Fill
5 , DataSet
Fill DataAdapter.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone " & _
"FROM Customers"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New DataSetQ
da.Fillfds, "Customers")

1 78

III : DataSet ADO.NET

Visual C# -NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone " +
"FROM Customers";
OleDbDataAdapter da = new 01eDbDataAdapter{strSQL, strConn);
DataSet ds = new DataSetQ;
da.Fill(ds, "Customers");

, , DataAdapter .
DataTable
DataAdapter DataTable. 4 DataReade.
.
.
, , , DataReader .

. ,
DataReader . DataTable
, DataReader. , ; DataReader .
DataTable . Columns DataTable DataColumn,
.
, DAO
ADO, Recordset Fields,
Field.
DataColumn
, DataColumn DataTable.
DataAdapterfill DataTable,
DataAdapter DataColumn, . DataColumn Name, Ordinal DataType,
DataColumn, DataAdapter fill,
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, OrderDate " &
"FROM Orders"

DataSel

179

Dim da As New 01eDbDataAdapter(strSQL, strConn)


Dim ds As New DataSetQ
da.FilKds, "Orders")
Dim tbl As DataTable = ds.Tables(O)
Console.WriteLineC'Column information for " & tbl.TableName &
" DataTable")
Dim col As DataColumn
For Each col In tbl.Columns
Console.WriteLine(vbTab & col.ColumnName & " - " & _
col.DataType.ToString)
Next col

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, OrderDate " +
"FROK

Orders";

OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);


DataSet ds = new DataSetQ;
da.FilKds, "Orders");
DataTable tbl = ds.Tables[0];
Console.WriteLineC'Column information for " + tbl.TableName +
11
DataTable");
foreach (DataColumn col in tbl.Columns)
Console.WriteLlne("\t" + col.ColumnName + " - " +
col.DataType.ToSt ring());
DataColumn , .
. DataColumn , DataAdapter DataTable.

, DataAdapter
DataTable
. Recordset ADO DAO, rdoResultset RDO DataReader ADO.NET . . Recordset rdoResultset
MoveFirst, MovePrevious,
MoveNexi MoveLast,
DataTable ADO.NET , XML-; . DataTable 24 . 7 , 365 ... , , .

180

III : DataSei ADO.NET

DataTable Rows,
DataRoiv, DataTable. , '
DataRow .
DataRow
DataRow DataTable. DataRoiv
DataTable, Rows .
DataRowCollection, DataRow.
-, DataRowCollection , .
Fill DataAdapter DataTable,
DataRoiv
.

Visual Basic .NET


Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT QrderlD, Customer-ID, EmployeelD, OrderDate " & _
"FROM Orders"

Dim da As New OleDbDataAdapterfstrSQL, strConn)


Dim ds As New DataSetO
da.FUKds, "Orders")
Dim tbl As DataTable = ds.Tables(O)
Dim row As DataRow = tbl.Rows(O)
Console.WriteLine("OrderID = " & row("Order!D"))
Console.WriteLine("CustomerID = " & row("CustomerID"))

Visual C# .NET
string strConn, strSQL;
StrConn = "Provider=SOLOLEDB;Data Source=(local)\\NetSDK; " +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, OrderDate " +
"FROM Orders";
OleDbDataAdapter da = new OleDbDataAdapterCstrSQL, strConn);
DataSet ds = new DataSetO;
da.Fillfds, "Orders");
DataTable tbl = ds.Tables[0];
DataRow row = tbl.Rows[0];
Console.WriteLine("OrderlD = " + row["OrderID"]);
Console.WrtteLineC'CustomerlD = " + row["CustomerID"]);
, DataRow DataTable,
, -

6 DataSet

181

DataReader. DataRow , . , , , DataTable. DataReader,


, . , .
DataRow
, DataRow't , , DataRow ?
DataReader, FieldCount , GetName Item . DataRow
FieldCount DataReader.
DataRow Table,
DataTable, DataRow. DataTable . DataRow
Table :
Visual Basic .NET
Private
Dim
Dim
For

Sub DisplayRowfByVal row As Dataflow)


tbl As DataTable = row.Table
col As DataColumn
Each col In tbl.Columns
Console.WriteLine(vbTab & col.ColumnName & ": " & row(col))
Next col

End Sub

Visual C# .NET
static void DisplayRow(Dataflow row)

{
DataTable tbl = row.Table;
foreach (DataColumn col in tbl.Columns)
Console.WriteLine("\t" + col.ColumnName + ": " + row[col]);

}
. Item DataRow DataColumn.
DataColumn ( 6%
), .
DataRow DataTable
DataRow DataTable , .NET Framework. For

1 82

111

: DataSet ADO. NET

For Each . DisplayRoiv DataTable, DataAdapterfitt.


Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK; " &
"Initial Catalog=Northwind;Trusted_Connection=Yes; "
strSQL = "SELECT OrderlD, CustomerlD. EmployeelD, OrderDate " & _
"FROM Orders"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New DataSetf)
da.FilKds, "Orders")
Dim
Dim
Dim
For

tbl As DataTable = ds.Tables(O)


row As DataRow
intCounter As Integer
Each row In tbl. Rows
intCounter += 1
Console. WriteLine{"Contents of row #" & intCounter)
DisplayRow(row)
Next row
Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB; Data Sou rce=( local )\\NetSDK; " +
"Initial Catalog=Northwind;Trusted_Connection=Yes; ";
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, OrderDate " +
"FHOM Orders";

OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);


DataSet ds = new DataSetO;
da.FilKds, "Orders");
DataTable tbl = ds.Tables[0];
int intCounter;
foreach (DataRow row in tbl. Rows)
intCounter++;
Console. WriteLinef'Contents of row ft" + intCounter);
DisplayRow(row);

DataSet
. North wind
. CustomerlD Customers 5
. Orders

6 DataSet

183

OrderlD , CustomerlD
Customers.
. , - . ,
.
,
. , , . , Web- , , , . .
DataSet ADO.NET , . ,
(constraints),
,
DataColumn,
DataColumn .
Readonly

. DataColumn , Readonly True,


AllowDBNulI

,
NULL. DataColumn AllowDBNulI, , DataSet NULL.
MaxLength

. , CustomerlD
Customers 5 , CompanyName
40 . DataColumn
MaxLength.
Unique

Unique DataColumn
. True ADO.NET
DataTable. ,
DataTable, , ADO.NET ConstraintException.

1 84

III : DataSet ADO.NET

Constraints DataTable
DataSet
DataTable. ADO.NET ,
DataTable, UniqueConstraint ForeignKeyConstraint; Constraint. DataTable
Constraints, , DataTable.
UniqueConstraint

Unique DataColumn True, DataTable, , .


Constraints DataTable UniqueConstraint. Unique 'DataColumn ,
UniqueConstraint Constraints DataTable.
UniqueConstraint , ,

.

.
DataRowCottection ADO.NET Find,
DataTable ( Find
8).
row = MyTable.Rows.FindC"ALFKI")

DataTable ,
. DataTable ForeignKeyConstraint

DataTable ' .
.
CustomerlD Orders North wind Customers. DataSet, ForeignKeyConstraint
Constraints DataTable, ,
ForeignKeyConstraint . DataRelation, DataTable
DataSet, ForeignKeyConstraint.
DataRelation
.
ADO.NET . , DataSet,
. .
, DataTable UniqueConstraint, CustomerlD. -

6 DataSet

185

, CustomerlD ZZZ2Z, ADO.NET , Data-Table ,



. DataTable Orders ,
CustomerlD DataTable Orders Customers, ADO.NET ,
CustomerlD
DataTable Customers. ,
CustomerlD , DataTable Customers, ADO.NET .
DataAdapter.FiliSchema
.
DataSet, DataAdapter, , DataColumn
Constraints DataTable,
DataTable DataAdapterftil.
DataAdapter,
DataTable ( ): MissingSchemaAction DataAdapter WithKey DataAdapterfillSchema ( 5).

, ...
ADO.NET
. DataSet
DataAdapter.
Dc&aAdapter
. Visual Studio .NET
DataSet DataAdapter ( ). , , DataAdapter
.
, ,
DataAdapterJFiUSchema
.
DataAdapter
FittSchema, DataColumn
DataAdapter , . DataColumn, , Readonly, AllowDBNulL MaxLengtb Unique
, DataAdapter DataTable . , .

186

III

: DaiaSet ADO.NET

DataAdapter , , . , DataAdapter . , DataAdapter , . , ,


, DataAdapter
DataTable.
DataAdapter Autolncrement
DataColumn. , 11.

DataTable
DataTable Fill FillSchema
DataAdapter ,
DataTable,
. ,
DataTable .
DataTable
DataTable , DataSet. DataTable
, TableName
:
Visual Basic .NET
Dim tbl As New DataTable("TableName")
Console,WriteLine(tbl.TableName)

Visual C# .NET
DataTable tbl = new DataTableC"TableName");
Console.WriteLIne(tbl.TableName);
DataTable Tables DataSet
DataTable DataTableCollectionAdd
Tables DataSet:
Visual Basic .NET
Dim ds As New DataSet{)
Dim tbl As New DataTable("Customers")
ds.Tables.Add(tbl)

Visual C# .NET
DataSet ds = new DataSetQ;
DataTable tbl = new DataTableC'Customers");
ds.Tables.Add(tbl);

6 DataSet

187

, - , Microsoft DatdTable Tables DataSet, Add DataTablesCollection.


DataTable Tables DataSet
:

Visual Basic .NET


Dim ds As New DataSet()
Dim tbl As DataTable = ds.Tables.Add("Customers")

Visual C# .NET
DataSet ds = new DataSetC);

DataTable tbl = ds.Tables.Actd("Customers");

, DataTable DataSet,
DataSet DataTable. DataTable
Tables DataSet, DataSet DataSet.
Nothing null,
. DataSet DataTable .
, DataTable DataSet. DataTable DataSet, Clone. DataTable
, DataTable.
Clone DataTable , ,
.
DataTable
* DataTable
. DataTable . , DataAdapter
DataColumn.
DataColumn. Columns Table ,
DataTable
Tables DataSet,
Visual Basic .NET
Dim ds As New DataSetO
Dim tbl As DataTable = ds.Tables.Add("Customers")
Dim col As DataColumn = tbl.Columns.Add("CustomerID")

Visual C# .NET
DataSet ds = new DataSetO;

DataTable tbl = ds.Tables.Add{"Customers"};


DataColumn col = tbl.Columns.AddC'CustomerlD");

1 88

III

: DalaSet ADO.NET

DataColumn
DataColumn
. DataColumn
DataType . Datatype
DataColumn , Rows
DataTable; .
DataColumn
, DataColumn ,
, Microsoft SQL Server . SQL Server, ,
,
(ANSI) (Unicode)
.
ADO.NET . ,
, , DataColumn
string. DataType DataColumn .NET, a
.
DataType DataColumn string.
DataColumn ,
. Add DataColum^Collection ColumnName DataType
DataColumn, DataTable:
Visual Basic .NET
Dim ds As New DataSetO
Dim tbl As DataTable = ds.Tables.Add("0rders")
Dim col As DataColumn = tbl.Columns.AddC'OrderlD", GetType(Integer))
Visual C# .NET
DataSet ds = new DataSetO;
DataTable tbl = ds.Tables.AdcK"Orders");
DataColumn col = tbl.Columns.AddC'OrderlD", typeof(int));

DataType Type. , , integer.


Visual Basic .NET Visual * .NET . .NET (/. C++,
Visual Basic,
. Visual Basic GetType .

, DataColumn
DataTable DataAdapter, . ,

6 DataSet

189

, DataColumn DataTable,
.
, AllowDBNull Readonly, MaxLength
Unique DataColumn , . .
Visual Basic .NET
Dim ds As New DataSet()
Dim tbl As DataTable = ds.Tables.Add{"Customers")
Dim col As DataColumn = tbl.Columns.AddC'CustomerlD")
col.AllowDBNull = False
col.MaxLength = 5
col.Unique = True

Visual C# .NET
DataSet ds = new DataSet();
DataTable tbl = ds.Tables.Add("Customers");
DataColumn col = tbl.Columns.AddC'CustomerlD");
col.AllowDBNull = false;
col.MaxLength = 5;
col.Unique = true;

DataTable .
PrimaryKey DataColumn, , .
DataTable , . . Customers
,CustomerlD, Order Details
OrderlD ProductlD. DataColumn
DataTable:
Visual Basic .NET
Dim ds As New DataSet)
' DataTable Customers
With ds,Tables,Add("Customers")
.Columns.Add("CustomerlD", GetType(String))
.PrimaryKey = New DataColumnO {.Columns("CustomerID")}
End With
' DataTable Order Details
With ds.Tables.Add("0rder Details")
.Columns.Add("OrderlD", GetType(Integer))
.Columns.Add("ProductlD", GetType(Integer))
.PrimaryKey = New DataColumnO {.Columns("OrderID"), _
.Columns("ProductlD")}
End With

1 90

III

: DataSet ADO.NET

Visual C# .NET
DataSet ds = new DataSetO;
DataTable tbl;
// DataTable Customers
tbl = ds.Tables.Add("Customers");
tbl. Columns. Add( "Customer-ID", typeof( string));
tbl.PrimaryKey = new DataColumn[] {tbl.Columns["CustomerID"]};
// DataTable Order Details
tbl = ds.Tables.Add("0rder Details");
tbl.Columns.Add("OrderID", typeof(int));
tbl.Columns.Add("ProductID", typeof(int));
tbl.PrimaryKey = new DataColumn[] {tbl.Columns["Order!D"],
tbl.Columns["ProductID"]};
DataTable,
ADO.NET DBNull DataColumn,
, False,

,
DataTable .
Constraints DataTable Add, Primary Key, UniqueKey ForeignKey.
Add
, .
DataTable Customers ,
CustomerlD, DataTable Order Details , OrderlD ProduclID. , Order
Details , , OrderlD Orders.
.
Constraint
Constraints DataTable. :
tbl.Constralnts.AddfNew UniqueConstraint(...))

Add ConstraintCollection ,
Constraint, UniqueConstraint
ForeignKey Constraint.
,
tbl. Constraints.Add("ConstraintName",

Columnlnformation)

Add PmnaryKey, UniqueKey


ForeignKey.

DataSet

191

, - .
, Add,
.
Visual Basic .NET
Dim ds As New DataSetQ
' DataTable Customers
With ds.Tables.Add("Customers")
.Columns.Add("CustomsrID", GetType(String
' , CustomerlD
,Constraints.Add(New UniqueConstraint(.Columns("CustomerlD"))
'
.Constraints.Add("UK_Customers", .Columns("CustomerlD"), False)
End With
' DataTable Order Details
With ds.Tables.Add("Order Details")
.Columns.Add("OrderID", GetTypeCInteger))
.Columns.Add("ProductID", GetType{Integer
' , OrderlD ProductID
Dim cols As New DataColumn() {.Columns("OrderID"), _
.Columns{"ProductID")}
.Constraints.Add(New UniqueConstraint(cols))
'
.Constraints.Add("UK_Order Details", cols, False)
' ForeignKeyConstraint, OrderlD
' OrderlD Orders
.Constraints.Add(New ForeignKeyConstraint
(ds.Tables("Orders").Columns("OrderlD"), _
.Columns("OrderIO")
'or
.Constraints.Add("FK_Order Details_0rders",
ds.Tables("Orders").Columns{"OrderlD"), _
,Columns("OrderID"
End With

Visual C# .NET
DataSet ds = new DataSetC);
DataTable tbl;
// DataTable Customers
tbl = ds. Tables.Add{"Customers"};
tbl,Columns.Add("CustomerlD", typeof(string));
// , CustomerlD
tbl.Constraints.Add(new UniqueConstraint(tbl.Columns["CustomerlD"]));
//

192

III : DataSet ADO.NET

tbl.Constraints.Add("UK_Customers", tbl.Columns["CustomerlD"],
false);
// DataTable Order Details
tbl = ds.Tables.Add("0rder Details");
tbl.Columns.Add("OrderID", typeof(int));
tbl.Columns.Add("ProductID", typeof(int));
// , OrderlD ProductID
DataColumn[] cols = new DataColumn[] {tbl.Columns["OrderID"],
tbl.Columnst"ProductID"]};
tbl.Constraints.Add{new UniqueConstraint(cols));
//
tbl.Constraints.Add("UK_Order Details", cols, false);
// ForeignKeyConstraint, OrderlD
// OrderlD Orders
tbl.Constraints.Add(new ForeignKeyConstraint
(ds.Tables["Orders"].Columns["OrderlD"],
tbl.Columns["OrderlD"]});
//
tbl.Constraints.Add("FK_Order Details_0rders",
ds.Tables["Orders"].Columns["OrderlD"],
tbl.Columns["OrderID"]);


ADO.NET () DataColumn Autolncrement,
AutoIncrementSeed AutolncrementStep,
, ADO.NET
, Autolncrement DataColumn True-.
Visual Basic .NET
Dim ds As New DataSetC)
Dim tbl As DataTable = ds.Tables.Add("0rders")
Dim col As DataColumn = tbl.Columns.Add("OrderID", GetType(Integer))
col.Autolncrement = True
col.AutoIncrementSeed = -1
col.AutoIncrementStep = -1
col.Readonly = True

Visual C# .NET
DataSet ds = new DataSetf);
DataTable tbl = ds.Tables.Add("0rders");
DataColumn col = tbl.Columns.Add("OrderID", typeof(int));
col.Autolncrement = true;
col.AutoIncrementSeed = -1;
ool.AutoIncrementStep = -1;
col.Readonly = true;

DataSet

193

OrderlD
AutoIncrementSeed AutoIncrementStep -1. , .
AutoIncrementSeed AutoIncrementStep , ADO.NET . , , ADO.NET
AutoIncrementSeed. ADO.NET
AutoIncrementStep.
, Autolncrernent True, AutoIncrementSeed
AutoIncrementStep 2, ADO.NET : 2, 4, 6, 8, 10.
DataTable DataAdapterfitt, . , DataTable, Orders
Northwind, AutoIncrementSeed AutoIncrementStep
DataColumn OrderlD 5. DataTable,
, OrderlD 5, 19, 15, 20 . ,
, DataTable, DataAdapterfill, DataTableRowsAdd,
OrderlD . ADO.NET , , DataTable, AutoIncrementStep.
, OrderlD
DataTable 973. , ADO.NET
AutoIncrementStep (5)
OrderlD 978.
, ADO.NET ,
DataTable. , , ADO.NET . ,
OrderlD DataTable, 973.
, :
SELECT OrderlD, CustomerlD, OrderDate FROM Orders WHERE CustomerlD = 'ALFKI'

OrderlD , DataTable.
ADO.NET , DataTable , .
, , ADO.NET. ,
ADO.NET,
ADO.NET .NET Framework
, DataTable DataTable.
,
, , ADO.NET
DataTable .

1 94

III : DafaSet ADO.NET

ADO.NET.

: ,
ADO.NET, , .
11 ,
DataTable.
: ,
. , ADO.NET. ,
, ADO.NET, .
, ,
, , ,
Order ID, ADO.NET, ,
?
: AutoIncrementSeed AutolncrementStep -1. , ADO.NET -, . ,
, ADO.NET , , ,
DataTable . . , ADO.NET
.
DataView DataRowView.
8, .
DataTable , DataView
DataTable .
, DataTable FittSchema. . .
. .
Visual Basic .NET
Dim ds As New DataSetO
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" i _
"Initial Catalog=Northwind;Trusted_Connectton=Yes;"
strSQL = "SELECT CustomerlD, CompanyName, ContactName " & _
"FROM Customers"

Dim da As New 01eDbDataAdapter(strSQL, strConn)


da.FillSchemafds, SchemaType.Source, "Customers")
Dim tbl As DataTable = ds.Tables("Customers")
Dim col As DataColumn = tbl.Columns.Add("RowID", GetType(lnteger))

6 DataSet

195

col.AutoIncrement = True
col.AutolncrementSeed = 1
col.AutoIncrementStep = 1
da.Fill(ds, "Customers")
Dim vue As New DataView(tbl)
Dim intPageSize As Integer = 10
Dim intPageNum As Integer = 3
vue.RowFilter = "RowID > " & (intPageNum - 1) * intPageSize &
" AND RowID <= " & intPageNum * intPageSize
Dim row As DataRowView
Dim intCounter As Integer
For intCounter = 0 to vue.Count - 1
row = vue(intCounter)
Console.WriteLine(row("RowID") & vDTab & row("CustomerID") &
vbTab & row("CompanyName"))
Next intCounter

Visual C# .NET
DataSet ds = new DataSetO;
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT CustomerlD, CompanyName, ContactName " +
"FROM Customers";
OleDbDataAdapter da = new OleDbDataAdapterfstrSQL, strConn);
da.FillSchema(ds, SchemaType.Source, "Customers");
DataTable tbl = ds.Tables["Customers"];
DataColumn col = tbl.Columns.Add("RowID", typeof(int));
col.AutoIncrement = true;
col.AutolncrementSeed = 1;
col.AutoIncrementStep = 1;
da.Fill(ds, "Customers");
DataView vue = new DataView(tbl);
int intPageSize = 10;
int intPageNum = 3;
vue.RowFilter = "RowID > " + (intPageNum - 1) * intPageSize +
" AND RowID <= " + intPageNum * intPageSize;
DataRowView row;
for (int intCounter = 0; intCounter < vue.Count; intCounter++) {
row = vue[intCounter];
Console.WriteLine(row["RowID"] + "\t" + row["CustomerID"] +
"\t" + row["CompanyName"]);
}

,:,
Web-? , . .
14. ,

ADO.NET.

1 96

III : DataSet ADO.NET

,
, . , Order Details
North wind
, .
, ,
.
,
. ,
:
SELECT OrderlD, ProductID, UnitPrice, Quantity,

UnitPrice * Quantity AS ItemTotal FROM [Order Details]


DataTable ,
. ,
DataTable UnitPrice Quantity,
. ,' . , .
ADO.NET DataColumn, ,
, ,
Expression DataColumn. , ADO.NET . ,
,
.
DataTable Order Detail
:
Visual Basic .NET
Dim ds As New DataSet<)
Dim tbl As DataTable = ds.Tables.Add("0rder Details")
tbl.Columns.Add("Quantity",
tbl.Columns.Add("UnitPrice",
tbl.Columns.Add("ItemTotal",
"Quantity *

GetType(Integer))
GetType(Decimal))
GetTypefDecimal),
UnitPrice")

Visual C# .NET
DataSet ds = new DataSetC):
DataTable tbl = ds.Tables.Add("0rder Details");
tbl.Columns.Add("Quantity", typeof(int));
tbl.Columns.Add("UnitPrice", typeof(Decimal));
tbl.Columns.Add("ItemTotal", typeof(Decimal),
"Quantity - UnitPrice");

6 DataSet

197

Northwind .
Order Details Discount,
. 0 1. Discount 0,25, 25 .
, :
Quantity * UnitPrice - (1 - Discount)
,
,
Northwind.
Expression , , DataTable DataSet.
, , ,
, . Expression MSDN.
DataTable,
Customers, Orders Order Details
DataSet, DataTable DataColumn.
DataSet,
DataSet, DataTable (
, DataTable ). DataColumn ( DataType,
AllowDBNull Autolncrement), UniqueKeyConstraint ForeignKeyConstraint,
DataSet, , ,
2 Data Form Wizard. DataSet ,
AutolncrementStep AutoIncrementSeed OrderlD DataTable Orders,
, ADO.NET
. , MaxLength
.
ForeignKeyConstraint, Relations
DataSet ( DataRelation ).
Data Form Wizard DataSet .
9;
DataSet , DataSet DataTable DataColumn, . DataSet :
Visual Basic .NET
Dim ds As New DataSetQ
Dim col As DataColumn

1 98

III

: DataSet ADO.NET

Dim fk As ForeignKeyConstraint
' customers
With ds.Tables.Add("Customers")
col = .Columns.Add("CustomerID", GetType(String))
col.MaxLength = 5
col = .Columns.AddC'CompanyName", GetType(String))
col.MaxLength = 40
col = .Columns.Add("ContactName", GetTypeCString))
col.MaxLength = 30
col = .Columns.Add("Phone", GetType(String))
col.MaxLength = 24
.PrimaryKey = New DataColumnO {.ColumnsC'CustomerlD")}
End With
' orders
With ds.Tables.AddC'Orders")
col = . Columns,AddC'OrderlD", GetType(Integer))
col.AutoIncrement = True
col.AutoIncrementSeed = -1
col.AutoIncrementstep = -1
col.Readonly = True

col = .Columns.AddC'CustomerlD", GetType(String))


col.AllowDBNull = False

col.HaxLength = 5
.Columns.Add("EmployeeID", GetType(Integer))
.Columns.Add("OrderDate", GetType(DateTime)}
.PrimaryKey = New DataColumnO {.Columns("QrderlD")>
End With
' order details
With ds.Tables.Add("0rder Details")
.Columns.AddC'OrderlD", GetType(Integer))
,Columns.AdcJC'ProductlD", GetType(Integer))
.Columns.Add("UnitPrice", GetType(Decimal))
col.AllowDBNull = False
col = .Columns.Add("Quantity", GetType(Integer))
col.AllowDBNull = False

col.DefaultValue = "1"
col = .Columns.Add("Discount", GetType(Decimal))
col.DefaultValue = "0"
,Columns.Add("ItemTotal", GetType(Decimal),
"UnitPrice Quantity * (1 - Discount)")
.PrimaryKey = New DataColumnO {.Columns("OrderID"),
.Columns{"ProductID")}
End With
' ForeignKeyConstraints
fk = New ForeignKeyConstraint(ds.Tables("Customers").ColumnsC'CustomerlD"),
ds.Tables("Orders").ColumnsC'CustomerlD"))

6 DataSet

ds.Tables("Orders").Constraints.Add(fk)
fk = New ForeignKeyConstraint(ds.Tables("Orders").Columns("QrderID"),
ds.TablesC"Order Details").Columns("OrderID"))
ds.Tables("Order Details").Constraints.Add(fk)

Visual C# .NET
DataSet ds = new DataSetO;
DataTable tbl;
DataColumn col;
ForeignKeyConstraint fk;
// customers
tbl = ds.Tables.Add("Customers");
col = tbl.Columns,Add{"CustomerID", typeof(string));

col.MaxLength = 5;
col = tbl.Columns.AddC'CompanyName", typeof(string));
eol.HaxLength = 40;
col = tbl.Columns.Add("ContactName", typeof(string));
col.MaxLength = 30;
col = tbl.Columns.AddC'Phone", typeof(string));
col.MaxLength = 24;
tbl.PrimaryKey = new DataColumn[] {tbl.Columns["CustomerID"]};
// orders
tbl = ds.Tables.Add("0rders");
col = tbl.Columns.AddC'OrderlD", typeof(int));
col.AutoIncrement = true;
col.AutoIncrementSeed = -1;
col.AutoIncrementStep = -1;
col.Readonly = true;
col = tbl.Columns.AddC'CustomerlD", typeof(strtng));
col.AllowDBNull = false;
col.MaxLength = 5;
tbl.Columns.Add("EmployeelD", typeof{int));
tbl.Columns.AddC'QrderDate", typeof(DateTime));
tbl.PrimaryKey = new DataColumn[] {tbl,Columns["OrderID"]};
// order details
tbl = ds.Tables.AddC'Order Details");
tbl. Columns. Add( "OrcterlD", typeof (int));
tbl.Columns.Add("ProductID", typeof(int));
col = tbl.Columns.Add("UnitPrice", typeof(Decimal));
col.AllowDBNull = false;
col = tbl.Columns.AddC'Quantity", typeof(int));
col.AllowDBNull = false;

col.OefaultValue = 1;
col = tbl.Columns,AddC'Discount", typeof(Decimal));
col.DefaultValue = 0;
tbl.Columns.Add("ItemTotal", typeof(Decimal),

199

200

III : DataSet ADO.NET

"UnitPrice * Quantity * (1 - Discount)");


tbl.PrimaryKey = new DataColumn[] {tbl.Columns["OrderID"],
tbl.Columns["ProductID"]};
// ForeignKeyConstratnts
fk = new ForeignKeyConstraint(ds.Tables["CustO!ners"].Columns["CustornerID''],
ds.Tables["Orders"].Columns["CustomerID"]);
ds,Tables["Orders"].Constraints.Add(fk);
fk = new ForeignKeyConstraint(ds.Tables["Orders"].Columns["OrderID"],
ds.Tables["Order Details"].Columns["OrderlD"]);
ds.Tables["Order Details"].Constraints.Add(fk);

DataTabie
DataSet, DataTabie DataColumn, DataTabie DataAdapter,
DataTabie. , , DataRow.
DataRow
DataSet . 5 , DataAdapter DataTabie
. , XML-;
12. ,
DataTabie Rows, DataRowCoUection,
DataRow, , DataRowCoUection Add. DataRow
ADO.NET .
, DataTabie, 10 DataRow, 10 DataRow.
, . . DataRow , . . , ? DataTabie
NewRow, DataRow
,
Visual Basic .NET
Dim row As DataRow = ds.Tables("Customers").NewRow
row("CustomerlD"} =: "ALFKI"
Visual C# .NET
Dataflow row = ds.Tables["Customers"].NewRow();
row["CustomerID"] =: "ALFKI";

DataRow, Item
. ,
. Item DataRow , -

DataSet

201

, .
DataRow, (
DataColumn) .
DataTableNewRow ,
DataTable. , , .
, , Null.
DataRow Rows, . CustomerlD
Customers Null . , DataTable Customers ,
CustomerlD.
Customers, CustomerlD, .
, DataTable, Add DataRoivCollection
:
Visual Basic .NET
Dim row As DataRow = ds.Tables("Customers").NewRow
row("dJStonierID") = "ALFKI"
ds.Tables("Customers").Rows.Add(row)
Visual C# .NET
DataRow row = ds.Tables["Customers"].NewRow();
row["CustoraerID"] = "ALFKI";
ds.Tables["Customers"].Rows.Add(row);

DataTable
LoadDataRoic.
, . ,
AcceptChanges, RowState
DataRow. False (. ),
RowState DataRow Added, DataTableNewRow RowsAdd.
Visual Basic .NET
Dim aValues As Object() = {"ALFKI", "Alfreds Futterkiste",
"Maria Anders", "030-0074321"}
ds.Tables("Customers").LoadDataRow(aValues, False)

8-5958

202

III : DataSet AOO.NET

Visual C# .NET
object[] aValues = {"ALFKI", "Alfreds Futterkiste",
"Maria Anders", "030-0074321"};
ds.Tables["Customers"].LoadDataRowCaValues,

false);

DataAdapterJUpdate,
DataAdapter RowState
DataRotc , ,
.
LoadDataRow True, RoicState
DataRow Unmodified, , , DataAdapter . RoivState
DataRow 10.

.
.
DataRow , Item . , .
, , .
Find Rows DataTable Customers CompanyName ContactName. Find 8. .
Visual Basic .NET
Dim rowCustomer As DataRow
rowCustomer = ds.Tables("Customers"),Rows.Find("ANTON")
If rowCustomer Is Nothing Then
' !
Else
rowCustomer("CompanyName"} = "NewCompanyName"
rowCustomer("ContactName") = "NewContactName"
End If
Visual C# .NET
DataRow rowCustomer;
rowCustomer = ds.Tables["Customers"].Rows.Find("ANTON"};
if (rowCustomer == null)
// !
else {
rowCustomer["CompanyName"] = "NewCompanyName";
rowCustomer["ContactName"] = "NewContactName";

,
BeginEdit EndEdit DataRow.

DataSet

203

Visual Basic .NET


Dim rowCustomer As DataRow
rowCustomer = ds.Tables("Customers").Rows,FindC'ANTON")
If rowCustomer Is Nothing Then
' !
Else
rowCustome .Beg inEdit
rowCustomerC'CompanyName") = "NewCompanyName"
rowCustomer("ContactName") = "NewContactName"
rowCustomer.EndEdit
End If

Visual C# .NET
DataRow rowCustomer;
rowCustomer = ds.Tables["Customers"].Rows.FindC'ANTON");
if (rowCustomer == null)
// !
else {
rowCustomer. BeginEditO;
rowCustomer["CompanyName"] = "NewCompanyName";
rowCustomer["ContactName"] = "NewContactName";
rowCustomer, EndEditO;
I
BeginEdit EndEdit .
EndEdit . ,
CancelEdit, BeginEdiL
. DataTable RoivCbanging, Ron-Changed, ColumnChanging ColwnnCbanged, . ,
BeginEdit EndEdit .

. DataTable , . BeginEdit, EndEdit ( CancelEdit, , ,
).
ItemArray, Item,
ItemArray .
, , a ItemArray
, .
Visual Basic .NET
Dim aCustomer As ObjectO = {"ALFKI", "NewCompanyName", _
"NewContactName", "NewPhoneNo"}

204

III

: DataSet ADO.NET

Dim rowCustomer As DataRow


rowCustomer = ds. Tables("Customers").Rows.Find("ALFKI")
rowCustomer. ItemArray = aCustomer

Visual C# .NET
object[] aCustomer = {"ALFKI", "NewCompanyName",
"NewContactName", "NewPhoneNo"};
DataRow rowCustomer;
rowCustomer = ds.Tables["Customers"].Rows.Find("ALFKI");
rowCustomer,ItemArray = aCustomer;

ItemAiTay
, Nothing (Visual
Basic) null (Visual C* .NET).
, .
Visual Basic .NET
Dim aCustomer As ObJectO = {Nothing, "NewCompanyName", _
"NewContactName", "NewPtioneNo"}
Dim rowCustomer As DataRow
rowCustomer = ds.Tables("Customers").Rows. Find("ALFKI")
rowCustomer.ItemArray = aCustomer
Visual C# .NET
object[] aCustomer = {null, "NewCompanyName",
"NewContactName", "NewPhoneNo"};
Dataflow rowCustomer;
rowCustomer = ds.Tables["Customers"].Rows.Find{"ALFKI">;
rowCustomer.ItemArray = aCustomer;

DataRow .
DataRow ,
DataAdapter.
10 11.
DataTablei
BeginEditw EndEdit, , . ,

.
, , BeginEditw EndEdit.
Null DataRow
- .NET , Null -

6 DataSet

205

. ,
Null, .
DataRow IsNull, ,
Null. DataRowJtem, IsNull , DataColumn.
, IsNull DataRow.
Visual Basic .NET
Dim rowCustomer As DataRow
rowCustomer = ds.Tables( "Customers"). Rows. Find("ALFKI")
If rowCustomer. IsNull("Phone") Then
Console. WriteLineC'It's Null")
Else
Console. WriteLineC'It's not Null")
End If

Visual C# .NET
DataRow rowCustomer;
rowCustomer = ds.Tables["Customers"]. Rows, FindC'ALFKI");
if { rowCustomer. IsNull( "Phone")}
Console. WriteLineC'It's Null");
else
Console. WriteLineC'It's not Null");
Null, Null
. System .NET Framework
DBNull, Value
Visual Basic .NET
Dim rowCustomer As DataRow
rowCustomer = ds.Tables("Customers"). Rows. FindC'ALFKI")
rowCustomerC'Phone") = DBNull. Value

Visual C# .NET
Dataflow rowCustomer;
rowCustomer = ds.Tables["Customers"]. Rows. FindC'ALFKI");
rowCustomer[ "Phone"] = DBNull. Value;

, , Delete
DataRow. .
DataTable. ADO. NET , . ADO.NET DataRow ?
, ADO.NET
, ,
. , DataRow.-

206

III

: DataSel ADO.NET

Delete, .
, . DataRow DataTable,
DataSet DataTable
.
10.
DataRow
- DataTable,
, Remove RemoveAt DataRowCollection, . DataRow,
Remove. , RemoveAt.

Visual Basic .NET


Dim rowCustomer As DataRow
rowCustomer = ds.Tables("Customers").Rows.Find("ALFKI")
ds.Tablesf"Customers").RemoveC rowCustomer)

ds.Tables("Customers").RemoveAt(intIndex)
Visual C# .NET
DataRow rowCustomer = ds.Tables["Customers"].Rows.FindC'ALFKI");
rowCustomer.ItemArray = aCustomer;
ds.Tables["Customers"].Remove(rowCustomer);

//
ds.Tables["Customers"].RemoveAt(intIndex);

Remove. RemoveAt DataRow, DataRow ,


.
, DataSet DataTable Clear, DataRoiv DataSet
DataTable.
DataRow.RowState
DataSet, DataTable DataRou- , .
.
, , . ADO.NET , . , , .
ADO.NET . 10.
. DataSet. Data-

6 DataSet

207

Ron' , ADO.NET ,
. , .

:
UPDATE HyTable SET FieldToHodify = NewValue
WHERE PKField = PKValue AND FieldToHodify = OriginalValue

INSERT INTO MyTable (Field!, Field2, .., FieldN)


VALUES (Value!, Value2, ... ValueN)

DELETE FROM MyTable WHERE PKField = PKValue


,
,
. ,
ADO.NET , DataRow.
ADO.NET RowState DataRoiv, DataRowState (. 6-1). , , , , (, ),
6-1. DataRowState

Unchanged
Detached
Added
Modified
Deleted

2
1
4
16
8


DataTable
DataTable,

, , RowState
DataRowState, . . 6-2
RowState.
6-2.
RowState

, DataTable:

RowState
Detached

row = tbl.NewRow
row("ColX") = "inltValue"
DataTable:

Added

tbl.Rows.Add(row)
. . .

208

III : DataSet ADO.NET

6-2.

()
RowState
Unchanged

:
row = tbl.Rows(O)
:

Modified

row.BeginEditO
row("ColX") = "NewValuel"
row.EndEdit()
:

Deleted

row.Delete()
Dataflow
, DataTable RowState . DataRoiv. , Item , .
Item
DataRowVersion (. 6-3).
6-3. DataRowVersion

Current
Original
Proposed
Default

512
1024
1536



(
BeginEdif)

, DataRow ,
, . . , , . CompanyName DataRow
() .
Visual Basic .NET
Dim rowCustomer As DataRow
rowCustomer = ds.Tables("Customers").Rows.FindC'ALFKI")
rowCustomer("CompanyName") = "NewCompanyName"
Dim strNewCompanyName, strOldCompanyName As String
Console.WriteLine(rowCustomer("CompanyName",
DataRowVersion.Current})
Console.WriteLine(rowCustomerf"CompanyName",
DataRowVersion.Original))

6 DataSet

'09

Visual C# .NET
DataRow rowCustomer;
rowCustomer = ds,Tables["Customers"].Rows.Find("ALFKI");
rowCustomer["CompanyName"] = "NewCompanyName";
string strNewCompanyName, strOldCompanyName;
Console.WriteLire(rowCustomer["CompanyName",
DataRowVe rsion.Cu rrent]);
Console.WriteLine(rowCustomer["CompanyName",
DataRowVersion.Original]);
BeginEditu End-Edit
DataRow .
EndEdit .
,
CancelEdit.
,
Item DataRow Proposed
DataRouVersion. Current BeginEdit (
, ).
DataRow , Item
DataRowVersion ( , ,
).
. 6-4 , Item DataRowVersion, . [] ,
Item DataRowVersion
.
6-4. DataRow

,
DataTable-.
row = tbl.NewHow
rowrColX") = "InitValue"

InitiaWalue

[] [] NewValue


DataTable:

InitialValue

[] []

RetrievedValue

RetrievedValue

NewValut

tbl.Rows.Add(row)

:

[] RetrievedValue

row = tbl.Rows(O)
. , .

210

111 : DalaSet ADO.NET

6-4.

()


[ :

RettieredValue

Retriei'edNeivValue 1
Value


NeuValue I

row.BeginEditO
row("ColX") = "NewValueV

:

[]

NewValuc I

RetrievedValue

NewValue I

NeicValue 1

Retrieved Value

NewValue 2

Retrieved Value

[] NeivValue 2

Neu'Value 2

Retrieved
Value

[]

[]

RetrievedValue

[] []

row.EndEdit()

:
row.BeginEditf)
rowfColX") = "NewValue2"

:
row.EndEditC)
:

NeicValue 2

row.BeginEditO
row("ColX") = "ValueToCancel"
row.CancelEditO
:
row.DeleteO

, . CancelEdit
BegmEdit ( , ).
, . .
, DataRotvVersion. Default RowState,
Item . DefaultValue. Default DataRowVersion
, Item DataKow,
, Item .
, .

DalaSet

211

, Item , DataRoivVersion.Current. Item, , .

DataSet
Visual Studio .NET
DataSet , . : !
Visual Studio .NET, DataSet.

DataSet
DataAdapter
, DataSet , DataAdapter,
DataSet Visual Studio .NET
DataSet DataAdapter.
, Windows- Web-, DataAdapter, DatuSet.
Data Generate Dataset, Properties
Generate Dataset Generate Dataset (. 6-1). Generate Dataset
(. 6-2).

. 6-1. Generate Dataset

212

N1 : DataSet ADO.NET

<5enetate a datasst that Deludes the specified tables,


Choose & dataset:

Choose whfcrt tablets) to add to


pi/Customers (dEbDataAdapte
iji/ Orders (QleDbDataAdapterZ)

ftddlhisdataset tolhecteiigriei-.

. 6-2. Generate Dacaset


DataSet. , DataAdapter,
DataSet. Generate Dataset
(. 6-2) DataAdapter, , . DataAdapter
DataSet. , Generate Dataset
, DataSet .
DataSet
. . 6-3 DataSet
. , Properties .
: Solution Explorer .xsd.
DataSet. ?* . Visual Studio .NET DataSet,
FillSchema DataAdapter, Generate Dataset,
WnteXmlScbema DataSet,
.
Visual Studio .NET ,
DataAdapterfillSchema, .
.xsd-, Generate
Dataset. Solution Explorer XML- Visual Studio .NET (. 6-4); .xsd- XML , DataSet, . DataTable -

6 DataSet

213

DataSet, DataColumn DataTable. , DataSet, DataTable


DataColumn, Properties .
<V Windowsftpphcaiipnl

Microsoft Sis

. [design] Forml.sMlteiign|

e*

.I e

. 6-3-

DataSet

Win.lawsAppl"sUianl Mtcrasofi ?iial Baiic .NET [desi^j DalaSeM .jifl


Sft

Edl

ft*

-'

" :

erolacf

~:

JjJ^uflontfs.
ft-
i OiivactName
L Phone

SSd

0e

-:^

i[CusCornfr<)

sfting
string

WindotHAppllcMkilil
iil R^er^fKEb
^ A^ssnblvJnfo.vb

50**! Q

. 6-4.

DataSet

214

III

: DataSet ADO.NET

DataSet
, DataSet, DataAdapter,
? Add New Item
(. 6-5) .xsd- DataSet.
A d d New (tern - WindowsApplicafienl
templates:

Canpcnent Class

User Control

Data Form Wizard

A File for creating an XML schema with DataSet classes


Name:

! Dataset2.xsd

Open

. 6-5-

DataSet

, DataSet, XML Schema,


Visual Studio .NET .xsd-
XML-. .xsd- DataSet , Visual Studio .NET , XML- DataSet.
DataSet, ,
DataSet DataAdapter, ,
DataSet . DataSet DataTable.
Acld\New Element
(. 6-6). Schema.
ADO.NET DataSet
XML-,
DataSet XML-. , . XML
, DataTable,
DataSet, , ,
XML, . ,
Visual Studio .NET DataSet, .
, DataSet
.

6 DataSet

I E.

215

NewglsmafiE

'. ;'A"; New attribute


I ~t~f
^f

New cranplexType
New srnpleType

New group
^,

New attributeuroup

<;

New any

^ft; New anv.Attribute

Generate Dataset

Preview Dataset...

. 6-6.

DataTable DataSet

DataTable taColumn. XML- ,


DataTable. .
, ,
DataTable (. 6-7). DataColumn,
Element .
ColumnName DataColumn,

. 6-7.

DataColumn DataTable

DataColumn,
XML- . . 6-8 ,
Properties . : DataColumn, XML-.
, ADO.NET, MaxLength DataColumn, Properties
.
DataSet ,
XML-.
DataSet, DataSet , Data Visual Studio .NET DataSet, ,
.
. Add
Dataset (. 6-9),

216

III : DataSet ADO.NET

''- Windomftpplitalniil . raual Basic .N11 | feijMi j Data:el2.art*

. 6-8.

DataColumn

Choose a typed or tnt^ed dataset to add to the designer.


< Typed dateset
Name : Wi ndo w s Applit a tio n 1 , Da t a Stt 1
Oeates an instance of a typed dateset da;s already m your project. Cheose tivs
to work vth a dataset that has a hult^n schema, See Heb for detafc on
generating typed daEasets.

' Untyped dataset


Creates an instance of an untyped dataset class trf type System. Data. PataSet.
Cfiaose this opnonwhen you want a dataset th no Khema.

Help

. 6-9. DataSet

DataSet. DataSet DataSet.
: DataSet , DataSet . . 6-10
Visual Basic .NET DataSet.

6 DataSet

WiadBWsAppScflliiml tticEtftofl Vfeunia<r"c -NE! Jdasienl

217

Mudutel.vb*

:ffl
Rdy

. 6-10.

DataSet

DataSet
, Visual Studio .NET DataSet ( 9). ,
? DataSet DataTable DataColumns ?
Add Dataset (. 6-9) , DataSet . , .
DataSet Visual
Studio .NET DataSet.
Add Dataset, Untyped Dataset
. DataSet.
Properties .
DataTable, Tables (...) Visual Studio .NET Collection Editor.
Visual Studio .NET. . 6-11 , DataTable,
DataSet.
Collection Editor DataColumn DataTable. DataColumn, Collection Editor DataTable. Columns (...). Collection Editor
(. 6-12), DataColumn.

218

III : DataSet ADO.NET

'- Tables Collection Editor


Table 1 Properties

Column;
(Collection)
Constraints
(Collection)
DisplayExpressio
, Minimum Capacity 50
i Namespace
: Prefix
fPrmaryKey
DataCoLrnn[]
hihlr i
DataTable I
Friend

dose

Help

. 6-11. DataTable
DataSet
Columns Collection Frtilor
Column I Pj

ullowDBNul
True
AutiS Increment Fal^e
AijtolncrementSf
Caption
DataType
; Def aufcvalue
I Express:on
SMaxLength
[... ni^'....

Column 1
L uluninl
5/stem, String
<DBNull>

I Prefix
! Readonly

. 6-12. DataColumn DataTable


DataColumn,
DataTable. Collection Editor DataTable, is PrimaryKey. , . DataTable (. 6-13). DataColumn,
DataTable
Collection Editor.

DataSel

219

Customers Properties:

- -. -'

13-

'"

! (DynarmcProoe't

-.

Columns

Collect

: CorstiEwts

on)

(Collection)

Uf OisplayExpressio
r MirihiumCapacity 50
Namespace
5

> - : Prefix
~J Data Col umn[]
' TableName

Add

Help

. 6-13.

DataTable

, Constraints
DataTable. Collection Editor Constraints
DataTable (...) .
Collection Editor (. 6-14), Constraints
DataTable. DataTable ,
, Constraints .
Constraint* Collection tditof
Ccnstrahtl Properties

Add -r 1

dit

Remove

Unique Constraint

Help

. 6-14.

DataTable

Collection Editor UniqueConstraint


ForeignKeyConstraint. Add, ,

III : DataSet ADO.NET

220

. . 6-15
UniqueConstraint.
DataColumn, .
, , Data-Table.
Unique Constraint

tome:
fconstraint;

CompanyName
ContactName
i CustomsrtD

ft-irnarytey

Help

. 6-15. UniqueConstraint
DataTable
. 6-16 ForeignKeyConstraint. ,
, 2 Customers Orders DataSet,
Fo reign Key Constrain!

. 6-16.
ForeignKeyConstraint DataTable

6 DataSel

221

DataSet, DataTable,
Data Column, DataRow, UniqueConstraint
ForeignKeyConstraint
DataSefvi ,
, .

DataSet
. 6-5 DataSet,
6-5.

DataSet

CaseSensitive
DatoSetName
DesignMode
EnforceConstraints
ExtendedProperties
HasErrors
Locale

Namespace

Prefix

Relations
Tables


Boolean

,
String
DataSet
Boolean
, DataSet
, DataSet Boolean

PropertyCollection

, DataSet
Boolean
Cultttrelnfo
, DataSet
,
String
ADO.NET DataSet XML-
XML- DataSet
Siring
, ADO.NET DataSet XML-
XML- DataSet
DataRelationCottection DataRelation. DataSet
DataTable, DataTableCollection
DataSet

CaseSensitive
CaseSensitive DataSet , DataSet. False.
CaseSensitive DataSet,
CaseSensitive DataTable
DataSet, .
DataTable CaseSensitive.

222

III

: DataSet ADO.NET

DataSetName
DataSetName DataSet.
DataSet. , DataSetName NewDataSet.
DataSet u XML- DataSetName . ,
,
XSD.exe XML-.
DesignMode
DesignMode , ,
DataSet . . DataSet , DesignMode True.
False.
DataTable DesignMode. .
EnforceConstraints
EnforceConstraints , DataSet
. True. ,
EnforceConstraints False.
EnforceConstraints True DataSet - , ADO.NET ConstraintException.
ExtendedProperties
ExtendedProperties DataSet . Property Collection,
. . ExtendedProperties , .
DataSet ,
ADO.NET ExtendedProperties .
DataTable, DataColumn, DataRelation Constraint ExtendedProperties.
, ExtendedProperties DataSet
:
Visual Basic .NET
Dim ds As New DataSetO
'
ds.ExtendedProperties,Add("Prop1", "Valuer1)
ds.ExtendedProperties.Add("Prop2", "Value2")
ds.Extended?roperties.Add{"Prop3", "Values")

DataSet

223

'
Console.WriteLlneCds.Extended?rties("Prop2"))
'
Dim objEnum As IDictionaryEnumerator
objEnum = ds.ExtendedProperties.GetEnumerator
Do While objEnum.MoveNext
Console.WriteLine(objEnum,Key & " = " & objEnum.Value)
Loop

Visual C# .NET
// "using System.Collections"
DataSet ds = new DataSet();
//
ds.ExtendedProperties.Add("Prop1", "Valuel");
ds.Extended?roperties.Add("Prop2", "Value2");
ds.Extended?roperties.Add("", "Values");
//
Console.WriteLine(ds.ExtendedProperties["Prop2"]);
//
IDictionaryEnumerator objEnum;
objEnum = ds. ExtendedProperties.GetEnumeratorO;
while (obj Enurn. MoveNext())
Console.WriteLine(objEnum.Key + " = " + objEnum.Value);

HasErrors
HasErrors , ,
DataRoic, DataSet, .
ContinueUpdateOnError DataAdapter
True, HasErrors
DataSet. , ,
DataTable DataRow HasEn~ors.

11.
Locale
.
DataSet ,
. Locale
DataSet.
Culturelnfo,
System.Globalization. Culturelnfo MSDN,
Locale DataSet, Locale DataTable DataSet, .

224

111 ' : DataSet ADO.NET

DataTable Locale.
Locale DataSet
English (Australia):

Visual Basic .NET


Dim ds As New DataSetO
ds.Locale = New System.Globalization.CultureInfo("en-AU")
Console. WriteLinefds.Locale.DisplayName)

Visual C# .NET
DataSet ds = new DataSetQ;
ds.Locale = new System.Globalization,CultureInfo("en-AU");
Console.WriteLlne(ds.Locale.DisplayName};
Namespace Prefix
Namespace / DataSet
XML. ADO.NET
DataSet XML-, XML-
DataSet.
DataTable DataRow Namespace Prefix.
XML MSDN,

Relations
Relations DataRelationCottection, DataSet DataRelation. , , DataRelation.
Tables
Tables , ,
DataRelation. DataTableCollection,
DataSet DataTable.
DataTable Tables
( TableName) . .

DataSet
. 6-6 DataSet.
6-6.

AcceptCbanges
Beginlnit
Clear
Clone

DataSet

DataSet
Visual Studio .NET
DataSet
DataSet DataRow
DataSet ,
DataRow

6-6.

DataSel

225

()

Endlnit

DataSet DataRow
Visual Studio .NET
DataSet
GetCbanges
DataSet ,
DataSet
GetXtnl
DataSet XML-
GetXmlSchema
DataSet XML-
HasChanges
, ,
DataRow DataSet
InferXmlScbema XML- ,
DataSet
Merge
DataSet, DataTable
DataRow DataSet
ReadXml
XML- DataSet , Stream,
TextReader XmlReader
ReadXmtScbema XML- DataSet ,
Stream, TextReader XmlReader
RejectCbanges
DataSet
Reset
DataSet,

WriteXml
DataSet XML- ,
Stream. TextReader XmlReader
WriteXmlSchema DataSet XML- ,
Stream, TextReader XmlReader

AcceptChanges RejectChanges
AcceptChanges RejectCbanges
DataSet.
DataRow, ADO.NET
RowState
Added, Modified Deleted, , ADO.NET
DataRow.
AcceptChanges DataSet ADO.NET
DataRow DataSet,
RowState , Added Modified, Unchanged. ADO.NET
DataRow\ . AcceptChanges DataSet DataRow, RowState Delete.
, DataRow,
DataAdapter DataRoivAcceptChanges.
RejectChanges DataSet
DataRow,

226

III

: DataSet ADO. NET

RoivState Added. RowState DataRou'


Modified Deleted, .
DataTable DataRow AcceptCbanges RejectChanges.
Beginlnit Endlnit
Beginlnit Endlnit , . Visual Studio .NET DataSet , , , . DataSetJSeginlnit, DataSet
Endlnit.
, , ,
, ( , , , ), .
DataTable Beginlnit

Clear
dear DataSet DataRou:
, DataSet .
DataTable Clear.
Clone
DataSet, . DataSet , , Clone.
DataTable Clone .
GetChanges
DatoSet.GetCbanges DataSet DataSet, DataSet
. 1 1,
DataTable GetChanges.
, DataSet, DataSet
DataRow. , , DataSet . DataSet ,
.

6 DataSet

227

GetXml GetXmlSchema
GetXml DataSet, , XML-.
, GetXmlSchema.
ADO.NET XML- 12.
HasChanges
HasChanges , ,
DataSet Data-Row ,
, DataSet
DataAdapter. DataSet , ?
Merge
Merge DataSet
DataSet, DataTable DataRow.
Merge 11.
ReadXml WriteXml
ReadXml DataSet XML- ,
TextReader, Stream XmlReader. XML- .
XmlReadMode , XML-
XML- XML-.
DataSet WriteXml,
XML-. ,
ReadXml
ADO.NET XML- 12.
ReadXmlSchema, WriteXmlSchema InferXmlSchema
ReadXmlSchema WriteXmlSchema ReadXml WriteXml,
XML-. ReadXml WriteXml,
TextReader, Stream, XmlReader XML.
InferXmlSchema ReadXmlSchema, ,
. Loading DataSet
Schema Information from XML MSDN.
ADO.NET XML- 12.
Reset
Reset DataSet,
.
DataSet, Reset, DataSet,

228

: DataSet ADO.NET

DataSet
. 6-7 DataSet.
6-7.

MergeFailed

DataSet

, DataSetMerge

MergeFailed
MergeFailed ,
Merge DataSet.
. , .

DataTable
. 6-8 DataTable.
6-8.

DataTable

CoseSensitive

Boolean

ChildRelations

DataRelationCollection

,
DataRelation DataTable

Columns

DalaColu mnCottection

DataColumn,
DataTable

Constraints

ConstraintCollection

Constraints, DataTable

DataSet

DataSet

DataSet, DataTable

DefaultView

DataView

DesignMode

Boolean

ExtendedProperties

PropertyCollection

DataView,
DataTable
, DataTable

, DataTable

HasEt-rors
Locale

Boolean
Culturelnfo

, DataTable

Namespace

String

,
ADO.NET DataTable XML- XML- DataTable

ParentRelations
Prefix

DataRelationCollection
String

DataRelation DataTable
, ADO.NET DataTable XML- XML- DataTable

6 DataSet

6-8.

()

Rows



DataColumn
DataRowCollection

TabteName

String

PrimaryKey

229


DataTable
DataColumn,
DataTable
DataTable

CaseSensitive
CaseSensitive DataTable , DataTable. DataSet CaseSensitive.
CaseSensitive DataTable ,
DataSet.
CaseSensitive DataTable, , DataSet.
CaseSensitive DataTable,
^'- DataSet False.
ChildRelations ParentRelations
ChildRelations ParentRelations DaiaRelations DataTable.
, (customers), (orders;
(order details) DataTable . ParentRelations DataRelation,
DataTable Customers Orders, ChildRelations DataRelation,
DataTable Orders Order Details.
Columns
Columns , ,
DataColumn. DataColumnCollection,
DataColumn DataTable.
DataColumn Columns
( ColumnName) ( Ordinal). , .
Constraints
Constraints , , DataTable . ConstraintsCollection.
DataColumn Columns
( ConstraintName) . ,

230

III : DataSet ADO.NET

DataSet
DataSet ,
DataTable. - DataSet,
.
DataSet .
DefaultView
DataTable ,
DataVieir, DefaultView
DataTable. , ,
DataGrid, DataTable,
(Spain). , DataTable - .
Visual Basic .NET
tblCustomers.DefaultView.RowFilter = "Country = 'Spain'"
grldCustomers.DataSource = tblCustomers

Visual C# .NET
tblCustomers,DefaultView.RowFilter = "Country = 'Spain'";
gridCustomers.DataSource = tblCustomers;
DataView 8.
DesignMode
DesignMode , ,
DataTable . . DataTable , DesignMode True.
False.
DataSet DesignMode.
.
ExtendedProperties
ExtendedProperties DataTable PropertyCollection,
.
DataSet, DataGolumn, DataRelation Constraint
ExtendedProperties.
, , ,
ExtendedProperties DataSet,
HasErrors
HasErrors , ,
DataRow DataTable .
ContinueUpdateOnError DataAdapter
True, HasErrors

6 DataSet

231

DataTabie. , .
DataSet DataRoiv HasErrors.

11.
Locale
Locale , ADO.NET DataTabie,
DataSet Locale.
, . ,
Locale DataSet,
MinimumCapacity
, DataTabie,
, , DataTabie , MinimumCapacity.
50, . . ADO.NET , , DataTabie 50 . DataTabie,
MinimumCapacity
. DataTabie
, .
DataTabie , ADO.NET , .
Namespace Prefix
Namespace Prefix DataTabie
XML. ADO.NET
DataTabie XML-, XML-
DataTabie.
DataSet DataRoiv Namespace Prefix,
XML MSDN.
PrimaryKey
PrimaryKev DataColumn. DataTabie.
. -, . DataRoiv . , DataTabie

DataColumn CustomerlD. DataTabie
,
, ADO.NET .
, DataRow DataTabie Find Rows
DataTabie. 8.

232

III : DataSet ADO.NET

DataTable.
Visual Basic .NET
Dim tbl As New DataTableC'Customers")
tbl.Columns.Add("CustomerID", GetTypefString))
tbl.Columns.Add("CompanyName", GetTypef String))
tbl.PrimaryKey = New DataColumnC) {tbl.Columns("CustomerID")}
Visual C# .NET
DataTable tbl = new DataTable("Customers");
tbl.Columns.AddC'CustomerlD", typeof(string));
tbl.Columns.Add("CompanyName", typeof(st ring));
tbl.PrimaryKey = new DataColumn[] {tbl.Columns["CustomerID"]};
Rows
Rows DataRowCollection, DataRow
DataTable.
DataRou- DataTable, .
DataRow DataTable
DataRowCollection. DataRow
8.

TableName
TableName DataTable.
DataTable.
DataTable XML-, TableName
DataTable.

DataTable
. 6-9 DataTable.
6-9.

DataTable

DataTable
Visual Studio .NET
DataTable
BeginLoadData
Clear
DataTable DataRow
Clone
DataTable ,
DataRow
Compute
, DataTable

DataTable
DataRow

AcceptChanges
Beginlnit

6 DataSet

233

6-9. ()

Endlnit
EndLoadData
GetCbanges
GetErrors
ImportRow
LoadDataRow
NewRow
RejectChanges
Reset
Select

Visual Studio .NET


DataTable

DataTable ,
DataTable
DataRow,
DataRow DataTable
DataTable DataRow,

DataTable DataRow
DataTable
DataTable,

DataRow

AcceptChanges RejectChanges
AcceptChanges RejectChanges
-DataTable.
DataSet DataRow AcceptChanges RejectChanges. " DataSet
.
Beginlnit Endlnit
Beginlnit Endlnit , .
DataSet Beginlnit Endlnit.
DataSet" ,
BeginLoadData EndLoadData
DataTable DataRow,
BeginLoadData EndLoadData.
BeginLoadData DataTable . EndLoadData.
DataTable , - , EndLoadData ADO.NET ConstraintException.
, ,
, GetErrors.

Clear
Clear DataTable DataRow.
, DataTable
.
DataSet Clear.

9-5958

234

III : DataSet ADO.NET

Clone
DataTable, . DataTabte , , Clone,
DataSet Clone .
Compute
Compute
DataTable .
Compute
, chai, .
Visual Basic .NET
Dim strSQL, strConn As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK; " & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, ProductID, Quantity FROM [Order Details]"
Dim da As New 01eDb.01eDbDataAdapter<strSQL, strConn)
Dim tbl As New DataTable("Order Details")
da.Fill(tbl)
Dim intNumChaiOrders As Integer
Dim IngtJumChaiUnits As Long
intNumChaiOrders = CInt(tbl.Compute("COUNT(OrderID)",
"ProductID = 1"))
LngNumChaiUnits = CLng(tbl.Compute("SUH(Quantity)",
"ProductID = V'))
Console.WriteLine("ff of orders that include chai: " &
intNumChaiOrders)
Console.WriteLine("Total number of units ordered: " &
IngNumChaiUnits)
Visual C# .NET
string strSQL, strConn;
strConn = "Provider=SQLQLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
StrSQL = "SELECT OrderlD, ProductID, Quantity FROM [Order Details]";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
DataTable tbl = new DataTableC'Order Details");
da.Fill(tbl);
int intNumChaiOrders;
Int64 intNumChaiUnlts;
intNumChaiOrders = (int) tbl.Compute("COUNT(OrderID)",
"ProductID = 1");
intNunChaiUnits = (Int64) tbl.Compute("SUM(Quantity>",
"ProductID = 1");
Console.WriteLine{"# of orders that include chai: " +
IntNumChaiOrders};

6 DataSet

235

Console.WrlteLine{"Total number of units ordered: " +


intNumChaiUnits);

Compute , SUM(Quantity * UnitPrice). .- Count:


SUM(ItemTotal).
Compute
Object. Compute , , , . .
Quantity 16- ,
Compute 64- .
, Compute, :
Visual Basic .NET
Dim objRetVal As Object = tbl,Compute("SUM(Quantity)",
"ProductlD = 1")
Console.WriteLine(objRetVal.GetType.ToString)
Visual C# .NET
object objRetVal = tbl.Compute("SUM(Quantity)",
"ProductlD = 1"};
Console.WriteLine(objRetVal.GetType().ToString()};
GetChanges
DataTable.GetChanges DataTable
DataTable, DataTable . 11.
DataSet GetChanges.
GetErrors
GetErrors DataRoiv, ,
DataRoiv,
ImportRow, LoadDataRow NewRow
ImportRow DataRoiv DataTable,
LoadDataRow , Columns DataTable.
, RowState
DataRow, RowState Added,
False; Unmodified,
True, LoadDataRow
DataRow.

236

III

: DataSet ADO.NET

NewRow DataTable DataRow,


Rows . , DataRow.
?
DataTable ImportRow.
, , LoadDataRow.
, NewRow.
NewRow.
Reset
Reset DataTable. . DataTable. Reset,
DataTable.
Select
Select DataTable . DataRow, .
Select 8.

DataTable
. 6-10 DataTable.
6-10.

ColumnCbanged
ColumnCbanging
RowCbanged
RowChanging
RowDeleted
RowDeleting

DataTable

ColumnChanged ColumnChanging
ColumnCbanged ColumnCbanging , . , , ..
DataColumnCbangeAveniArgs, Row Column, ,
.
: .

6 DataSet

237

RowChanged Row/Changing
RowChanged RowChanging ,
DataRow RowState .
, , Action DataColumnChangeAventArgs . Row .
RowDeteted RowDeleting
RowDeleted RowDeleting ,
RowChanged RowChanging. ,
DataTable.

DataColumn
. 6-11 DataColumn.
6-11.

DataColumn

AllowDBNull

Boolean

,
Null

Autolncrement

Boolean

, . ADO.NET !

AutoIncrementSeed

Integer

AutoIncrementStep

Integer

Caption

String

,
DataGrid

ColumnMapping

MappingType

, ADO.NET
XML-

ColumnName

String

DataColumn

DataType

Type

DefauttValue

Object

, ADO.NET

Expression

String

, ADO.NET
,

ExtendedProperties

PropertyCollection

MaxLengtb

Integer

Namespace

String

, ADO.NEiT
DataSet
XML- XML-
DataSet

Ordinal

Integer


DataColumn Columns DataTable

Prefix

String

, ADO.NET DataSet
XML- XML-
DataSet
. . .

238

III : DataSet ADO.NET

6-11.

()

Readonly


Boolean

Table

DataTable

Unique

Boolean

,

DataTable,
DataColumn
,

DataTable

AllowDBNull
AllowDBNull , DataColumn
Null. DataColumn True.
DataColumn DataAdapterFill
AllowDBNull True,
Null. Fill,
DataAdapter . DataTable, FillSchema,
Autolncrement, AutolncrementSeed AutolncrementStep
, ADO.NET .
Autolncrement True, ADO.NET . False. AllowDBNull,
Autolncrement DataColumn, , True, DataAdapterfillScbema.
Autolncrement True, ADO.NET AutolncrementSeed AutolncrementStep. AutolncrementSeed 0.
AutolncrementStep 1. ,
ADO.NET,
-1. DataAdapterfillScbema AutolncrementSeed AutolncrementStep.
,
ADO.NET .
, a ADO.NET - DataSet.
Caption
Caption , DataTable DataGnd. Caption , ColumnName.
, Caption - ,
, ColumnName.

DataSet

239

ColumnMapping
ColumnMapping , ADO.NET , DataSet XML-.
MappingType, SystemData. ColumnMapping
Element, . . DataRoir . ColumnMapping
Attribute, Hidden SimpleContent.
, DataSet .

Column.ColumnMapping = MappingType.Element
<MyDataSet>
<Customers>
<CustomerID>ABCuE</Cu5tomerID>
<CompanyName>New Customs r</CompanyName>
<ContactName>New Contact</ContactName>
<Phone>425 555-1212</Phone>
</Customers>
</MyDataSet>

Column.ColumnMapping = MappingType.Attribute
<HyDataSet>
<Customers CustomerID="ABCDE" CompanyName="New Customer"
ContactName="fJew Contact" Phone="425 555-1212" />
</MyDataSet>
ADO.NET XML- 12.
ColumnName
ColumnName DataColumn.
DataColumn.
DataType
DataType , ADO.NET
. ,
ADO.NET .NET.
, ADO,
, .
, SQL Server
, . ADO -.
DataColumn ADO.NET, .
DataType . , DataType DataColumn DataColumnCollectionAdd:

240

III

: DataSet ADO.NET

Visual Basic .NET


Dim col As New DataColumnC'NewColumn")
col.DataType = GetTypeCDecimal)
Dim tbl As New DataTable("Products")
tbl.Columns.AddC'ProductlD", GetType(Integer))
tbl.Columns.AddC'ProductName", GetType(String))
tbl.Columns.Add("UnitPrice", GetType(Decimal)}

Visual C# .NET
DataColumn col = new DataColumnC'NewColumn");
col.DataType = typeof(Decimal);
DataTable tbl = new DataTableC'Products");
tbl.Columns.AddC'ProductlD", typeof(int));
tbl.Columns.Add("ProductName", typeof(string));
tbl.Columns.AddC'UnitPrice", typeof(Decimal));
DefaultValue
DefaultValue DataColumn .
SQL Server .
DefaultValue DataColumn , SQL Server.
SQL Server,
. SQL Server ,
.
DefaultValue
Object. , . DefultValue OrderDate
. . OrderDate
, .
DefaultValue , , SQL Server.
Expression
Expression , ADO.NET . ( ), ReadOnly DataColumn True.
, Expression DataColumn,
Quantity UnitPrice
DataTable. , DataTable DataRow
.

DaiaSet

241

Visual Basic .NET


Dim tbl As New DataTable("Order Details")
tbl. Columns. Add( "OrderlD" , GetType( Integer) )
tbl. Columns, Add("ProductID", GetType(Integer))
tbl. Columns. Add( "Quantity", GetType(Integer)}
tbl. Columns. Add{"UnitPrlce", GetType( Decimal))
Dim col As New DataColumn("ItemTotal", GetType(Decimal))
col. Expression = "Quantity * UnitPrice"
tbl. Columns. Add(col)
Dim row As OataRow = tbl.NewRow()
row("OrderID") = 1
row("ProductID") = 1
row("Quantity") = 6
row( "UnitPrice") = 18
tbl. Rows. Add(row)
Console. WriteLine(row("ItemTotal"))

Visual C# .NET
DataTable tbl = new DataTable( "Order Details");
tbl. Columns. Add( "OrderlD", typeof(int));
tbl. Columns. AddC'ProductID", typeof(int));
tbl. Columns. Add( "Quantity", typeof(int));
tbl. Columns. Add( "UnitPrice", typeof (Decimal));
DataColumn col = new DataColumn("ItemTotal", typeof(Decimal));
col. Expression = "Quantity * UnitPrice"
tbl. Columns. Add(col);
DataRow row = tbl.NewRow();
row["OrderID"] = 1;
row["ProductID"] = 1;
row["Quantity"] = 6;
row["UnitPrice"] = 18;
tbl. Rows. Add( row);
Console. WriteLine( row["ItemTotal " ] ) ;
,
DataTable 7.
Expression MSDN.
ExtendedProperties
ExtendedProperties DataColumn tion, .
DataSet. DataTable, DataRelation Constraint ExtendedProperties.
, , /,
ExtendedProperties DataSet.

MaxLength ,
DataColumn , .

242

III : DataSet ADO. NET

1, . .
. AllowDbNull Autolncrement, DataAdapterFill Maxlength.
DataAdapterfittSchema.
Namespace Prefix
Namespace Prefix DataSet
XML. ADO. NET
DataSet XML-, XML-
DataSet.
DataSet DataTable Namespace Prefix.
XML MSDN,
Ordinal
Ordinal DataColumn
Columns DataTable. ,
DataColumn - DataTable, -/.

Readonly , . False.
Expression DataColumn
( ), Readonly True.
Readonly .
, Readonly True, ADO. NET ReadOnlyException. ,
Readonly True, DataRow
Rows DataTable .
AllowDbNull Autolncrement, Readonly FillSchema, Fill DataAdapter.
Table
Table DataTable, DataColumn.
Columns - DataTable,
.
Unique
Unique DataTable. False,
Unique True, DataTable,
DataColumn, UniqueConstraint. , UniqueConstraint, , Unique DataColumn
True.
, ADO.NET Unique DataColumn True,

6 DataSet

243

. , Order Details Norchwind OrderlD ProductlD.


, , .
AlloicDbNull Autolncrement, Unique FittSchema, Fill DataAdapter.

Dataflow
. 6-12 DataRow.
6-12,

DataRow

Ron-Error


Boolean
Object
Object
String

RowState

DataRoivState

Table

DataTabla

HosErrors
Item

ItemArrav

,
/
/
/


DataTable,

HasErrors
HasErrors , DataRow .
.

Item
Item
.
, DataColumn.
, Item DataRou'Version, , . ,
,
ItemArray
ItemArray
. Object, DataTable.
ItemArray
, Nothing (Visual Basic)
null (Visual C* .NET). , .
DataTable,
.

Visual Basic .NET


row.ItemArray = New Object() {Nothing, 2, 3, 4, Nothing}

244

III : DataSet ADO.NET

Visual C# .NET
row.ItemArray = new object[] {null, 2, 3, 4, null};
RowError
RowError
. , ,
RowError .
HasErrors DataRow True, RowError .
SetColumnError.
RowState
RowState DataRowState. . .
RowState .
Table
Table DataTable, DataRow;
.
DataRow Rows - DataTable , DataTable NetvRow
Rows DataTable. Table
DataTable, DataRow.

DataRow
. 6-13 DataRow.
6-13.

DataRow

AcceptChanges
BeginEdit
CancelEdit
ClearErrors

DataRow
DataRow
, BeginEdit
DataRow
DataRow

Delete

EndEdit
GetCbildRows
GetColumnError
GetColumnsInError
GetParentRow
GetParentRows

,
BeginEdit
DataRow
DataRow, Data-Relation

DataColumn,
DataRow
DataRow, DataRelation
DataRow
DataRow, DataRi'latiou

6 DataSet

245

6-13. -()

HasVersion
IsNult

RejectCbanges
SetColumnError
SetParentRow

, ,
DataRow
, DataRow Null

DataRow

DataRow DataRow,
DataRelation

AcceptChanges RejectChanges
AcceptChanges RejectChanges
DataRow.
, ,
DataRow, DataAdapter DataRowAcceptChanges.
RowState DataRow Unmodified.
RejectChanges DataSet
; RowState DataRow
Unmodified.
, , . CompanyName Initial
CompanyName, New CompanyName.
AcceptChanges DataRow Initial CompanyName.
DataRowItem, DataRow New CompanyName.
RejectChanges DataRow
New CompanyName. DataRowItem, DataRow Initial
CompanyName.
, ADO.NET DataRow
, 10 11.
BeginEdit, CancelEdit EndEdit
BeginEdit, CancelEdit EndEdit
DataRow. ,

.
CancelEdit EndEdit ,
AcceptCbanges RejectCbanges. . DataRow, , BeginEdit,
DataRow .

246

III : DataSet ADO.NET

Visual Basic .NET


Dim tbl As New DataTable("Customers")
, Columns. Add( "Customer-ID", GetType( String
tbl.Columns.Add("CompanyName", GetType(String))
Dim row As Dataflow
' LoaddataRow
row = tbl.LoadOataRow(New Object() {"ABODE",
"Initial CompanyName"}, True)
' DataRow
' row.RowState Modified
'"" - "Initial CompanyName"
rowC'CompanyName") = "New CompanyName"
' BeginEnit CompanyName
row.BeginEdit()
rowC'CompanyName"} = "Even Newer CompanyName!"
'
Console.WriteLine("Proposed: " &
rowC'CompanyName",
Console.WriteLine("Current: " & _
rowC'CompanyName",
Console.WriteLineC'Original: " &
rowC'CompanyName",

DataRowVersion.Proposed))
DataRowVersion.Cur rent))
DataRowVersion.Original))

Visual C# .NET
DataTable tbl = new DataTable("Customers");
tbl.Columns.AddC'CustomerlD", typeof(string));
tbl.Columns.Add("CompanyName", typeof(string));
DataRow row;
// LoadDataRow
row = tbl.LoadDataRow(new object[] {"ABCDE",
"Initial CompanyName"}, true);
// DataRow
// row.RowState Modified
//"" - "Initial CompanyName"
row["CompanyName"] = "New CompanyName":
// BeginEnit CompanyName
row. BeginEditO;
row["CompanyName"] = "Even Newer CompanyName!";
//
Console.WriteLineC'Proposed: " +
row["CompanyName", DataRowVersion.Proposed]);

6 DataSel

247

Console.WriteLine("Current: " +
row["CompanyName", DataRowVersion.Current]};
Console.WriteLine("Original: " +
row[ "CorfipanyNarae", DataRowVersion .Original ]);

, , Even Newer
CompanyName!, New CompanyName Initial
CompanyName.
EndEdit. .
.
, CancelEdit. .
:
BeginEdit, DataRowJtem . DataRow .
ClearErrors
ClearErrors DataRou- .
DataRoic ,
.
Delete
Delete Rows
Datalable. ADO.NET
,
DataAdapter.Update,
- DataRow, Delete AcceptChanges. DataRowCollectionRemove.
GetChildRows
GetChildRou's
DataRow DataRelation .
, GetChildRoivs DataRowVersion.
GetChildRows
DataRoii.
GetColumnError SetColumnError
GetColumnError SetColumnError
. ,
DataTable DataColumn,
SetColumnError , .

248

III

: DataSet ADO.NET

GetColumnslnError
HasErrors DataRow True, GetColumnslnError
, DataRow .
GetColumnslnError GetColumnError DataRow.
Visual Basic .NET
Dim row As DataRow
If row.HasErrors Then
Console.WriteLine("The row contains the following errors:")
Console.WriteLineC'RowError: " i row.RowError)
Dim colError As DataColumn
For Each colError In row.GetColumnsInError
Console.WriteLineC'Error in " & colError.ColumnName & ": " & _
row.GetColumnError(colError))
Next colError
Else
Console.WriteLine("The row does not contain errors")
End If

Visual C# .NET
DataRow row;
if

{row.HasErrors)

Console.Writel_ine("The row contains the following errors:");


Console.WriteLineC'RowError: " + row.RowError);
foreach (DataColumn colError in row.GetColumnsInErrorO)
Console.WriteLineC'Error in " + colError.ColutnnName + ": " +
row.GetColumnError(colError));
,

else
Console.WriteLineC'The row does not contain errors");
GetParentRow, GetParentRows SetParentRow
GetParentRow, GetParentRows SetParentRow
DataRow DataRelation.
GetChildRows, GetParentRows DataRelation
, DataRouVersion,
. GetParentRows DataRow.
DataRow , GetParentRows,
, GetParentRow, DataRow.

6 DataSet

249

SetParentRow DataRow.
DataRow . DataRow DataTahle,
,
DataSet, SetParentRow,
DataRelation, , .

Has Version
, DataRoiv , . .
, RowState Added, DataRow , . DataRow,
RowState Deleted, '/
.
HasVersion , DataRoiv . DataRowVersion
, , DataRow .
IsNult
, DataRow
ContactName .
ContactName null,
:
Visual Basic .NET
Dim row As DataRow
Dim strContactName As String
strContactName = CStr{row("ContactName"))

Visual C# .NET
DataRow row;
string strContactName;
strContactName = (string) row["ContactName"];

DataSet , null,
null.
IsNull . , DataColurnn
, , null.
.-

250

III : DataSet ADO.NET

Visual Basic .NET


Dim row As Dataflow
Dim strContactName As String
If row.IsNull("ContactName") Then
StrContactName = "<Null>"
Else
StrContactName = CStr(row("ContactName"))

End If

Visual C# .NET
Dataflow row;
string strContactName;
if (row.IsNullC'ContactName"))
StrContactName = "<Null>";
else
strContactName = (string) row["ContactName"];
IsNutt DataColumn
DataRoivVersion. IsNull , null.

UniqueConstraint
. 6-14 UniqueConstraint.
6-14.

Columns

UniqueConstraint

ConstraintName
ExtendedProperties



DataColumn
String
PropertyCollection

IsPrimaryKey

Boolean

Table

DataTable

,




,
DataTable
DataTable,

Columns
Columns DataColumn, , . .

ConstraintName
ConstraintName UniqueConstraint.

6 DataSet

251

ExtendedProperties
ExtendedProperties UniqueConstraint PropertyCollection, .
DataSet, DataColumn, DataRelation ForeignKeyConstraint ExtendedProperties.
, , ,
ExtendedProperties DataSet.
IsPrimaryKey
IsPrimaryKey , ,
UniqueConstraint DataTable.
. UniqueConstraint DataTable ,
, DataTable,
PrimaryKey .
Table
Table DataTable, UniqueConstraint; .

ForeignKeyConstraint
. 6-15 ForeignKeyConstraint.
6-15. ForeignKeyConstraint

AcceptRejectRule

AcceptRejectRule

Columns


DataColumn

, AcceptCbanges RejectCbanges DataRou'


,


, DataRoic


,



ConstraintName
DeleteRule
ExtendedProperties
RelatedCoIttmns
RelatedTable
Table
UpdateRule

String
Rule

PropertyCollection

DataColumn
DataTable
DataTable
Rule

AcceptRejectRule, DeleteRule UpdateRule


AcceptRejectRule, DeleteRule u UpdateRule .

252

III

: DataSet ADO. NET

,
None, . . AcceptCbanges
RejectRule DataRow .
AcceptRejectRule Cascade, , ForeignKey Constraint,
DeleteRule UpdateRule , Rule. Cascade, . . .
, Delete DataRow Delete . , DataRow, .
, DeleteRule
UpdateRule None. SetNutt SetDefault.
null, .
Columns RetatedColumns
Columns DataColumn, , . RelatedColumns
.
.
ConstraintName
ConstraintName ForeignKeyConstraint.

ExtendedProperties
ExtendedProperties ForeignKeyConstraint tyCollection, .
DataSet, DataColumn, DataRelation UniqueConstraint ExtendedProperties.
, , ,
ExtendedProperties DataSet.
RelatedTable Table
RelatedTable , Table
DataTable . .

,
. DataSet
?
. DataTable,
DataSet. DataSet

6 DataSet

253

, , XML-. , DataTable.
. DataTable , , ,
PrimatyKeyConstraint.

. ADO. NET , DataSet. Primary KeyConstraint,
DataTable .
ADO. NET - ,
.

. Item 1 DataRowVersion.Original.
. , ?
. . RejectChanges DataRou', DataTable DataSet
,
.
.

, DataTable ?
:

Visual Basic .NET


If tbl.PrimaryKey. Length > 0 Then
' DataTable
Else
' DataTable
End If

Visual C# .NET
if (tbl.PrimaryKey. Length > 0)
// DataTable
else
// DataTable

DataSet Dispose?

. DataSet, DataTable DataColumn


MarsbalByValueComponent, Dispose Disposed.
Dispose .
Dispose ,
Disposed ,

254

III : DataSet ADO.NET

, Dispose - , , .
Dispose DataSet Dispose
DataTabte DataSet.

1 . . 7-1 , Northwind, SQL Server 2000, , , , .


,
.
, .
DataTable , , , , . , * .
, - .

, , . , , , .
,
. , : , , .
DataTable DataRelation ADO.NET. ForeignKey'Constraint, .

256

1)1 : DataSet ADO.NET

Employees
E Employee'lD
La^iMane
FntrvVKI

Customers
~

CornDanvNamf

"^ COTeetTt*.

-.*i;i.
risiomerlD
EmployealD
^QrderDite

3hlpptete
3l*Vn
Prwrjhl

~CU

PostalCode

J*

" " i^)

__ TM=

Eithtatr
HirsDWS
Address

|
|

L
.

Oriter DetaUs

ProducU

.:_

Supplier IP
.-I,H
J Crsmunt

1
^

i'.'

UlltMtB

'

....

~1 Catagaryriam?
*~J Df^cnption
QPl*"

. 7-1.

Northwind


, ADO.NET
.
.
, DataRelation.


Microsoft. , . Customers, Orders Order Details Northwind:
SELECT C.CustomerlD, C.CompanyName, C.ContactName, C.Phone,
0.OrderlD, O.EmployeelD, O.OrderDate,
D.ProductID, D.Quantity, D.UnitPrice
FROM Customers C, Orders 0, [Order Details] D
WHERE C.CustomerlD = 0. Customer-ID AND 0. OrderlD = D.OrderlD

:
.
;
;
. , ,
.

257

.
.
100 , (. 7-2).

ALFKI
ALFKl
-ALFKJ
ALf
IALFKI
III
ALFKI
JALJKI
iANAIP
IANATR
ANATF
ANATP
ANATP
ANATFi

ANATFI

D30-007432
D3D-007432
D3D-007432
D3D-007432
D3D-007432
D3D-007432
030-7432
03D407432

. Til ll,l'i I.
4lflli Fiiiskisle
Alfre* Fultarkifli
Alfre* FuHnkitle
Alfred! FuKekitle
Alfred: Fglaftele
..

, .

D3D4M7432
.' .
.51566.4729
.5) 555-4729

,,.

Ana ~iifa
"

. .

EmpaiEda]
a Empaadad
Ana Tnio Eriparedad
rparedad
Ana Tnjlo inperffdad

.5) 555-4729
5) 555-4723
(5) 555-4729
(5) 5-172
(] -4729
(] 55-472
(5) 555-472S
(5) 555-472S
(5) 555-3932
15) 555-3932
(5) 555-3932
(5) 555-32
.5) 555-3932
(5) 555-3932
[5) 555.3932
(5) 555-3S32
[5] 555-3932
[5] 655-3932

. 7-2. ,
.
, ADO.NET, , . ,
, ,
, ? , ,
,
?
. (,
), , .


,
ADO, ,
.
:

258

III : DataSet ADO.NET

, ;
. (, Recordset),
, ADO ;
. , .
;
.
, ,
Recordset ,
Recordset ;
. , ,
, , -, . .

Recordset ADO
ADO 2.0 Recordset.
. Customers, Orders Order Details
Recordset:
Dim rsCustomers As ADODB,Recordset, rsOrders As ADODB.Recorders
Dim rsOrderDetails As ADODB.Recordset
Dim strConn As String, strSQL As String
strConn = "Provider=MSDataShape;Data Provider=SQLOLEDB;" &
"Data Source=(local)\NetSDK;Initial Catalog=Nc>rthwind;" &
"Trusted_Connection=Yes;"
strSQL = "SHAPE {SELECT CustomerlD, CompanyName, ContactName, " &
"ContactTitle FROM Customers} AS Customers APPEND " & _
"((SHAPE {SELECT OrderlD, CustomerlD, EmployeelD, OrderDate " 4
"FROM Orders} AS Orders APPEND ({SELECT OrderlD, ProductID, " &
"UnitPrice, Quantity FROM [Order Details]} AS OrderDetaiLs " &
"RELATE "OrderlD" TO 'OrderlD') AS OrcferDetails) AS Orders " & _
"RELATE 'CustomerlD' TO 'CustomerlD'} AS Orders"
Set rsCustomers = New ADOOB.Recordset
rsCustomers.Open strSQL, strConn, adOpenStatic, adLockBatchOptimistic
Set rsOrders = rsCustomers.Fields("0rders").Value
Set rsOrderDetails = rsOrders.Fields("OrderDetails").Value

Recordset , , .
Recordset , Recordset .

259

Recordset :
, ;
;
. ,
Recordset ,
. .
Recordset :
. - ! ADO, SHAPE;
. ;
;
.

DataRelation ADO.NET
DataRelation ADO.NET Recordset. DataRelation
SHAPE. DataRelation
DataSet.
, DataRelation
Recordset .
* DataRelation.
DataRelation :
, ;
;
;
. , ,
. ,
Orders Order Details,
Order Details , . 11;
. ,
, ;
. ,
,
ForeignKeyConstraint, DataRelation;
.
SQL Server Oracle? .

260

111 : DataSet ADO.NET

DataRelation :
. , DataRelation
, .
.

DataRelation
, ,
. DataRelation ADO.NET. ,
DataRelation.

DataRelation
DataRelation , . DataRelation , ; , , .
, DataRelation , DataColumn
.
, , DataTable, (. 7-3). DataRelation :
Visual Basic .NET
' DataSet DataTable DataColumn
Dim ds As New DataSet()
' DataRelation,
Dim rel As DataRelation
rel = New DataRelation("CustomersOrders",
ds.TablesC"Customers").Columns("CustomerlD"),
ds.Tables("Qrders").Columns( "Customer-ID"
ds.Relationships.Add(rel)

Visual C# .NET
// DataSet DataTable DataColumn
DataSet ds = new DataSetO;
// DataRelation,
DataRelation rel;
rel = new DataRelation{"CustomersOrders",
ds.Tables["Custome rs"].ColumnsE"CustomerlD"],

261

ds.Tables["Orders"].Columns["CustomerID"]);
ds.Relationships.Add(rel);

B/3/19
/1
3/1
/I 1 , /II
/II./19
4/l'l1
f
nj llii In
/JB/19
/B/199
1/H8/1
/-1/19

5 ..,,,1
1B35E.
IB183
S3 S8 -

/28/19
Hum
I/IS/I
2/16/1
/21/19
/4/199

7
97

!,i,
9V

8
96
96
7

. 7-3-
, , DataRelation, DataColumn:
Visual Basic .NET
' DataSet DataTable DataColumn
Dim ds As New DataSetC)
' DataColumn,
' DataRelation
Dim colsParent, colsChiLd As DataColumnO
With ds.Tables("ParentTable")
colsParent = New DataColumnO {.Columns("ParentColumn1"), _
.Columns("ParentColumn2")}
End With
With ds,Tables("ChildTable")
colsChild = New DataColumnO {.Columns("ChildColumn1"), _
.Columns("ChildColumn2")}
End With
' DataRelation
Dim rel As DataRelatlon
rel = New DataRelation("MultipleColunms", colsParent, colsChild)
ds.Relationships.Add(rel)

Visual C# .NET
// DataSet DataTable DataColumn
DataSet ds = new DataSetO;
// DataColumn,
// DataRelation

262

III

: DataSel ADO.NET

DataTable tblParent, tblChlld;


DataColumn[] colsParent, colsChild;
tblParent = ds.Tables["ParentTable"];
colsParent = new DataColumn[] {tblParent.Columns["Paren1:Column1"],
tblParent.Columns["ParentColumn2"]};
tblChild = ds.Tables["ChildTable"];
colsChild = new DataColumn[] {tblChild.ColumnsE"ChildColumn1"],

tblChild.Coluns["ChildColun2"]};
// DataRelation
DataRelation rel;
rel = new DataRelation("MultipleColumns", colsParent, colsChild);
ds.Relationships,Add(rel);

, DataRelation , , , ,
,
.
DataRelation DataTable ( ). .
DataRelation Relations
DataSet. DataTable DataColumn,
DataRelation Relations DataSet :
Visual Basic .NET
' DataSet DataTable DataColumn
Dim ds As New DataSet()
' DaiaRelation,
ds.Relationships.Add("CustomsrsOrders",
ds.Tables{"Customers").ColumnsC'CustomerlD"),
ds.Tables("Orders").Columns( "Customer-ID"))

Visual C# .NET
// DataSet DataTable DataColumn
DataSet ds = new DataSetO;
// DataRelation,
ds.Relationships.Add("CustomersOrders",
ds.Tables["Customers"].Columns["CustomerlD"],
ds.Tables["Orders"].Columns["CustomerID"]);


DataRelation
DataTable. DataRelation

263

GetCbiidRotvs, GetParentRoiv GetParentRows DataRow. DataRelation ?


DataRelation. ,
,
GetChildRows DataRow

DataTable . GetCbudRows
DataRow DataRelation, DataTable. DataRelation. GetChildRows
DataRoiv.
GetChildRows ;
Visual Basic .NET
'
Din rowCustomer, rowOrder As DataRow
For Each rowCustomer In ds.Tables("Customers").Rows
Console, WriteLine(rowCustomer("CustomerID") & " - " & _
rowCustomer("CompanyName"))
' ,
For Each rowQrder In rowCustomer. GetChildRowsC'fielationName")
Console. WriteLine(vbTab & rowOrder("Order!D") & " - " * _
rowOrder("OrderDate"
Next rowOrder
Next rowCustomer

Visual C# .NET
//
foreach (DataRow rowCustomer in ds,Tables["Customers"].Rows)

{
Console. WriteLine(rowCustomer["CustomerID"] + " - " +
rowCustomer [ "CompanyName" ]);
// ,
foreach (DataRow rowOrder in rowCustomer. GetChildRowsC'RelationName"))
Console. WriteLine("\t" + rowOrder["OrderID"] + " - " +
rowO rde r [ " 0 rde rDate " ] ) ;

GetParentRow DataRow
DataRelation ,
. DataRow GetParentRoiv,
DataSet DataRelation. GetChildRows, GetParentRow
DataRelation :

264

III

: DataSet ADO.NET

Visual Basic .NET


Dim rowCustomer, rowOrder As DataRow
'
For Each rowOrder In ds.TablesC'Orders").Rows
Console.Write(rowOrder("OrderIO") & vbTab & rowOrder("OrderDate")}
'
rowCustomer = rowOrder.GetParentRow("CustomersOrders")
Console.WriteLine(vbTab & rowCustomer("CompanyName"))
Next rowOrder
Visual C# .NET
DataRow rowCustomer;
//
foreach (DataRow rowOrder in ds.Tables["Orders"].Rows)

I
Console.Write(rowOrder["OrderID"] + "\t" + rowOrder["OrderDate"]);
//
rowCustomer = rowOrder.GetParentRow{"CustomersOrders");
Console.WriteLine("\t" + rowCustomer["CompanyName"]);

'
GetParentRows . DataRow

DataRow,
GetParentRows DataRow.
GetChildRows-.
Visual Basic .NET
'
Dim rowChild, rowParent As DataRow
For Each rowChild In ds.Tables("ChildTable").Rows
' ,
Console.WriteLine(rowChild("ChildName"))
For Each rowParent In rowChild.GetParentRows{"RelationName")
Console.WriteLine(vbTab i rowParent("ParentName"))
Next rowParent
Next rowChild
Visual C# .NET
//
foreach (DataRow rowChild in ds.Tables["ChildTable"]. Rows)

{
Console. WriteLine(rowChild["ChildName"]);
// '
foreach (DataRow rowParent in rowChild.GetChildRows("RelationName"))
Console.WriteLine("\t" + rowParent["ParentName";|);

265

*,
.

, ,
.
.
DataSet ,
( 12).
, , ,
. ,
DataSet.
6 , Item DataRow
. , GetCbildRows, GetParentRow GetParentRows
DataRow DataRowVersion,
.
,
,
:
Visual Basic .NET
'
Dim rowCustomer, rowOrder As DataRow
For Each rowCustomer In ds.Tables("Customers").Rows
Console.WriteLine(rowCustomer("CustomerID") i " " & _
rowCustomer("CompanyName"))
' ,
'
For Each rowOrder In rowCustomer.GetChildRowsC'RelationName", _
DataRowVersion.Original)
Console.WriteLine(vbTab & rowOrder("OrderID") & " - " & _
rowOrder{"OrderDate"))
Next rowOrder
Next rowCustomer

Visual C# .NET
//
foreacn (DataRow rowCustomer in ds.Tables["Customers"].Rows)

1
Console.WriteLine(rowCustomer["CustomerID"] + " - " +
rowCustome r [" CoinpanyName" ]);
// ,
//
foreach {DataRow rowOrder in rowCustomer.GetChildRowsC'RelationName",

10-5956

266

III

: DataSet ADO.NET

DataRowVersion.Original))
Console,WriteLine("\t" + rowOrder["OrderlD"] + " rowOrder["OrderDate"]);

, DataRowVersion, ,

DataRelation
, DataRelation DataTable,
DataRelation .
Data-Table DataTable , . . Orders , Customers. DataRelation
DataTable.

DataRelation DataTable
UntqueKey, DataTable ForeignKey Constraint. CustomerlD DataTable Customers UniqueKey, CustomerlD
DataTable Orders ForeignKeyConstraint.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK; " &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.OpenO
StrSQL = "SELECT CustomerlD, CompanyName, ContactName FROM Customers"
Dim daCustomers As New 01eDbDataAdapter(strSQL, en)
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, OrderDate FROM Orders"
Dim daOrders As New 01eDbDataAdapter(strSQL, en)
Dim ds As New DataSetQ
daCustomers.Fill(ds, "Customers")
daOrders.Fill(ds, "Orders")
en.Close()
ds,Relationships.Add("CustomersOrders",
ds.Tables("Customers").Columns("GustomerlD"),
ds.Tables("Orders").Columns("CustomerlD"))
Console.WriteLine("The parent DataTable now contains " &
ds.Tables("Customers").Constraints.Count &

267

" constraints")
Console.WriteLine("The child DataTable now contains " &
ds.Tables("Orders").Constraints.Count 4
" constraints")

Visual C# .NET
string strConn, strSOL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
en.Open();
strSQL = "SELECT CustomerlD, CompanyName, ContactName FROM Customers";
OleDbDataAdapter daCustomers = new 01eDbDataAdapter{strSQL, en);
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, OrderDate FROM Orders";
OleDbDataAdapter daOrders = new 01eDbDataAdapter(strSQL, en);
DataSet ds = new DataSetQ;
daCustomers.Fill(ds, "Customers");
daOrders.Fill(ds, "Orders");
cn.CloseO;
ds.Relationships.Add("CustomsrsOrders",
ds.Tables["Customers"].Columns["CustomerlD"],
ds.Tables["Orders"].Columns["CuEitomerID"]);
Console.WriteLine("The parent DataTable now contains " +
<3s. Tables[ "Customers"]. Constraints. Count +
" constraints");
Console.WriteLineC'The child DataTable now contains " +
ds.Tables["Orders"].Constraints.Count +
" constraints");

; DataRelation
, :
Visual Basic .NET
Dim ds As New DataSetO
daCustomers.Fill(ds, "Customers")
uaOrders.Fill(ds, "Orders")
cn.CloseO
With ds.Tables("Customers")
.PrimaryKey = New DataColumnO {.Columns("CustomerID")}
End With
With ds.TablesC'Orders")
.Constraints.Add("FK_CustomersOrders", _

268

III : DataSet ADO.NET


ds.TablesC"Customsrs").Columns("CustomsrID"), _
.ColumnsC"Custome rID"))

End With
us. Relationships.Add("CustomersOrders", _
ds.TablesC"Customers").ColumnsC"GustomerlD"), _
ds.Tables("Orders").Columns("CustomerID"))
Console.WriteLineC"The parent DataTable now contains " &
ds.Tables("Customers").Constraints.Count &
" constraints")
Console.WriteLineC"The child DataTable now contains " & _
ds.TablesC"Orders").Constraints.Count &
" constraints")
Visual C# .NET
DataSet ds = new DataSetO;
daCustomers.Fill(ds, "Customers");
daOrders.FillCds, "Orders");
cn.CloseC);
DataTable tbl = ds.Tables["Customers"];
tbl.PrimaryKev = new DataColumn[] {tbl.Colufnns["CustomerlD"]};
tbl = ds.Tables["Orders"];
tbl.Constraints,Add("FK_CustomersOrders",
ds.Tables["Customers"].Columns["CustomerID"],
tbl.Columns["CustoraerID"]);
ds. Relationships.Add("CustomersOrders",
ds.Tables["Customers"].Columns["CustomerID"],
ds,Tables["Orders"].Columns["CustomeirID"]);
Console.WriteLineC"The parent DataTable now contains " +
ds.TablesC"Customers"].Constraints.Count +
" constraints");
Console.WriteLineC"The child DataTable now contains " +
ds.Tables["Orders"].Constraints,Count +
" constraints");
-! !
, DataRelation ADO.NET DataSet UniqueKey ForeignKeyConstraint, DataRelation.
DalaSet , DataRelation
. ADO.NET .

269

. , DataRelation, , , ADO.NET
DataRelation.
, DataRelation,
DataSet.
ForeignKeyConstraint Null
, . , ,
ForeignKeyCon&traint
DataSet .
?
. Norhtwind ( - ADO.NET ).
UPDATE Orders SET Customer!!) = NULL WHERE CustOfflerlO = 'ALFKI 1
, Orders , .
- Customers.
:
UPDATE Orders SET CustomerlD = 'ALFKI' WHERE CustofflerlD IS NULL

, Orders ForeignKeyConstraint Y, , .
Customers , CustomerlD ZZZZZ,
:
UPDATE Orders SET CustomerlD = 'ZZZZZ' WHERE CustomerlD = 'ANTON'

, , ForeignKeyConstraint, MULL,
. , DataSet.

DataRelation,
, ,
. Employees Northwind.
EmpIoyeelD , ReportsTo
. , ReportsTo
FOREIGN KEY, , EmpIoyeelD.
Employees
DataSet DataRelation:

Visual Basic .NET


Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
StrSQL = "SELECT EmpIoyeelD, ReportsTo, " &
"LastName + ', ' + FirstName AS EmployeeName FROM Employees"

270

III : DataSet ADO.NET

Dim da As New 01eDbDataAdapter{strSQL, strConn)


Dim ds As New DataSetQ
da.Fill(ds, "Employees")
Dim tbl As DataTable = ds.TablesC'Employees")
ds.ftelations.Add("SelfReferencing", tbl.Columns("EmployeeID"), _
tblColumnsC"ReportsTo"), False)
Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK; " +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
StrSQL = "SELECT EmployeelD, ReportsTo, " +
"LastName + ', ' + FirstName AS EmployeeName FROM Employees";
QleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strCcnn);
DataSet ds = new DataSetO;
da.FilKds, "Employees");
DataTable tbl = ds.Tables["Employees"];
ds.Relations.Add("SelfReferencing", tbl.Columns["EmployeelD"],
tbl.Columnst"ReportsTo"], false);
DataRelation . (. 7-4).
, .
, .

. 7-4. Employees
DataRelaHon
DataTable . Employees
, ReportsTo NULL.
NULL ForeignKey Constraint -
ForeignKey Constraint Null.
, , , -

271

, ,
- .
!
Visual Basic .NET
Dim row As Dataflow
For Each row In tbl.Rows
If row.IsNull("ReportsTo") Then
DisplayRow(row, "")
End If
Next row
Public Sub DisplayRow(DataRow row, string strlndent)
Console.WriteLine{strIndent i rowC'EmployeeName"))
Dim rowChild As DataRow
For Each rowChild in row.GetChildRows("SelfReferencing")
DisplayRow(rowChild, strlndent & vbTab)
Next rowChild
End Sub

Visual C# .NET
foreach (DataRow row in tbl.Rows)
if (row.IsNull("ReportsTo"))
DisplayRowfrow, "");
static votd DisplayRow(DataRow row, string strlndent)
{
Console.WriteLine(strIndent + row["EmployeeName"]};
foreach (DataRow rowChild in row.GetChildRows("SelfReferencing"))
DisplayRow(rowChild, strlndent + "\t"};


Employees, ReportsTo 7. , , .
, ,
.


.
, ,
. ,
. , .
authors titles pubs SQL Server.

272

III : DataSet ADO.NET

, , ,
. ForeignKeyConstraint,
.
, , . .
pubs titleauthor (. 7-5), .
, au_id title_id
authors titles .

. 7-5. authors, titles titleauthor pubs SQL Server


, . titleauthor
. ,
titleauthor .
, .
.
DataRelation, authors titleauthor, titles
titleauthor. DataTable authors,
DataRelation .
Visual Basic .NET
Dim strConn, strSQL. as string
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK; " &

7
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.OpenO
Dim daAuthors, daTitles, daTitleAuthor As OleDbDataAOapter
strSQL = "SELECT au_id, au_lname, au^fname FROM authors"
daAuthors = New 01eDbDataAdapter(strSQL, en)
StrSQL = "SELECT title.id, title FROM titles"
daTitles = New 01eDbDataAdapter{strSQL, en)
strSQL = "SELECT au_id, title.id FROM titleauthor"
daTitleAuthor = New 01eDbDataAdapter(strSQL, en)
Dim ds As New DataSetQ
daAuthors.Fill(ds, "authors")
daTitles.Fill(ds, "titles")
daTitleAuthor.Fill(ds, "titleauthor")
cn.CloseO
ds.Relations.Add{"authors_titleauthor", _
ds.TablesC"authors").Columns("au_id"), _
ds.Tablesf"titleauthor").Columnsf"au_id"),
False)
ds.Relations.Add("titles_titleauthor", _
ds.Tablest"titles").Columns("title_id"), _
ds.Tables("titleautnor"),Columns("title_id"),
False)
Dim rowAuthor, rowTitle, rowTitleAuthor As DataRow
For Each rowAuthor In ds.Tables("authors").Rows
Console.WriteLine(rowAuthor("au_lname") & ", " & rowAuthor("au_fname"))
For Each rowTitleAuthor In _
rowAuthor.GetChildRowsC'authors_titleauthor")
rowTitle = rowTitleAuthor.GetParentRow("titles_titleauthor")
Console.WriteLine(vbTab & rowTitle("title"))
Next rowTitleAuthor
Next rowAuthor

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenO;
OleDbDataAdapter dsAuthors, dsTitles, dsTitleAuthor;
strSQL = "SELECT au^id, au_lname, au_fname FROM authors";
daAuthors = new 01eDbDataAdapter(strSQL, en)
strSQL = "SELECT title.id, title FROM titles";
daTitles = new 01eDbDataAdapter(strSQL, en);
strSQL = "SELECT au_id, title^id FROM titleauthor";
daTitleAuthor = new 01eDbDataAdapter(strSQL, en);

273

274

III : DataSet ADO.NET

DataSet ds = new DataSetO;


daAuthors. Fill{ds, "authors"};
daTitles.FillCds, "titles");
daTitleAuthor.Fill(ds, "titleauthor");
cn.CloseO;
ds.Relations.Add("authors_titleauthor",
ds.Tables["authors"].Columns["au_id"],
ds.Tables["titleauthor"].Columns["au_id"],
false);
ds.Relations.Add("titles_titleauthor",
ds.Tables["titles"].Columns["title_id"],
ds.Tables["titleauthor"].Columns["title_ld"],
false);
foreach {DataRow rowAuthor in ds.Tables["authors"].Rows)

{
Console.Writel_ine(rowAuthor["au_lname"] + ", " +
rowAuthor["au_fname"]);
foreach (DataRow rowTitleAuthor in
rowAuthor.GetChildRows("authors_titleauthor"))

{
DataRow rowTitle;
rowTitle = rowTitleAuthor.GetParentRow("titles_titleauthor");
Console.WriteLine("\t" + rowTitle["title"]);

DataReiation
DataColumn,
6 , Expression DataColumn
DataColumn, Quantity
' UnitPrice. , DataColumn
DataRelation
, ,
.
DataRelation
Expression DataColumn.
DataTabie Orders Order Details, Data-Table Order Details
DataColumn ItemTotal. Data-Column, .
DataColumn . , Expression DataColumn :
Count(Child.ProductlD)
,
DataTabie

275

DataTable. , :
Count(Child(RelationName).ProductID)
DataColumn DataColumn
ItemTotal DataTable. Expression
DataColumn , DataColumn:
Sum(Child,ItemTotal)
Visual Basic .NET
Dim ds As New DataSetQ
ds.Relations.Add("OrdersOrderDetails",
ds,Tables("Orders").Columns("QrderID"),
ds.Tables("Order Details").Columns("OrderID"))
ds.Tables("Order Details").Columns.Add("ItemTotal", GetType(Decimal),
"Quantity - UnitPrice")
ds.Tables("Orders").Columns.Add("NumItems", GetType(Integer),
"Count(ChiLd.ProductlD)")
ds.Tables("Orders"),Columns.Add("OrderTotal", GetType(Decimal),
"Sum(Child.ItemTotal)")

Visual C# .NET
DataSet ds = new DataSetO;
ds.Relations.Add("OrdersOrderDetails",
ds.Tables["Qrders"].Columns["OrderID"],
ds.Tables["Order Details"].Columns["OrderID"]);
ds.Tables["Order Details"].Columns.Add("ItemTotal", typeof(Decimal),
"Quantity * UnitPrice");
ds.Tables["Orders"].Columns.Add("NumItems", typeof(int),
"Count(Child.ProductlD)");
ds.Tables["Orders"],Columns.Add("OrderTotal", typeof(Decimal),
"Sum(Child.ItemTotal)");
DataColumn
DataTable.
* author title pubs: ,
.
, DataTable titleauthor
DataColumn, DataTable titleauthor title DataColumn title.
DataTable
GetParentRow.

276

III : DataSet ADO.NET

Visual Basic .NET


Dim ds As New DataSetO
ds.Relations.Add("authors_titleauthor", _
ds.TablesC"authors").ColumnsC"au_id"), _
ds.Tables("titleauthor").Columns{"au_id"),
False)
ds.Relations,Add("titles_titleauthor", _
ds.Tables("titles").Columns("title_id"),
ds.Tables("titleauthor").Columns("title_id"), _
False)
ds.TablesC"titleauthor").Columns.Add("title", GetType(String), _
"Parent(titles_titleauthor).title")
Dim rowAuthor, rowTitleAuthor As Dataflow
For Each rowAuthor In ds.TablesC"authors").Rows
Console.WriteLine(rowAuthorC"au_lname") & ", " A rowAuthor("au_fname"))
For Each rowTitleAuthor In
rowAuthor.OetChildRows("authors_titleauthor")
Console.Writel_ine(vbTab & rowTitleAutnor("title"))
Next rowTitleAuthor
Next rowAuthor
Visual C# .NET
DataSet ds = new DataSetO;

ds.Relations.Add("authors_titleauthor",
ds,Tables["authors"].Columns["au_id"],
ds.Tables["titleauthor"].Columns["au_id"],
false);
ds.Relations.AddC"titles_titleauthor",
ds.Tables["titles"].Columns["title_id"],
d$.Tables["titleauthor"].Columns["title_id"],
false);
ds.Tables["titleauthor"].Columns.Add{"title",

typeof(string),

"Parent(titles_titleauthof).title");
foreach (DataRow rowAuthor in ds.Tables["authors"].Rows)
{

Console.WriteLine(rowAuthor["au_lname"] + ", " +


rowAuthor["au_fname"]>;
foreach (DataRow rowTitleAuthor in
rowAuthor.GetChildRows("authors_titleauthor"))

277

Console.WriteLine("\t" + rowTitleAuthor["title"]);
Expression MSDN.


. , , , ,
.
- .
FOREIGN KEY Order Details Northwind SQL Server ,
Orders ,
Order Details. SQL Server 2000 FOREIGN KEY. FOREIGN KEY
,
. . 7-6 SQL Server 2000
FOREIGN KEY.

Efforts relationship I;: INSERTS anc UPMiSs


- jpHtoto Jidatci Fields

. 7-6. FOREIGN
KEY SQL Server 2000
ForeignKeyConstraint ADO.NET . DeleteRule UpdateRule, ,
,
FOREIGN KEY.
DeleteRule UpdateRule ForeignKeyConstraint
DeleteRule UpdateRule Rule, SystemData.
Cascade, . . DataTable

278

III

: DataSet ADO.NET

DataTable.
DataTable, FOREIGN KEY (, CustomerlD
DataTable Customers), DataTable,
DeleteRule UpdateRule None, SetDefault
SetNutt. DeleteRule None, DataTable .
NULL, DeleteRule / UpdateRule NULL. ,
SelDefault, , FOREIGN KEY, Default.


. , ,
, DataTable,
. 10, DataAdapter , DataTable
. ,
DataTable
DataTable, .
?
, . , . ,
. , , :
SELECT CustomerlD, CompanyName, ContactName, Phone
FROM Customers WHERE Country = 'Canada'

Orders,
, . Orders Country,
, Customers:
SELECT 0. Order-ID, 0. CustomerlO, 0. Employ ID, O.OrderDate
FROM Customers C, Orders 0
WHERE C.CustomerlD = O.OrderlD AND C.Country = 'Canada 1

279

DataRelation
Visual Studio .NET
DataRelation, ,
Visual Studio .NET.

DataRelation DataSet

6 , DataSet
Visual Studio .NET. DataSet
XML Schema Designer, DataSet (*.xsd)
Solution Explorer.
DataTable, , Add\New Relation (. 7-7).
Schema Visual Studio .NET. (. 7-8). DataRelation.
*, lViiiiloHAp|ilir.)ln>n1 Microuifl I'isii..! (3.14,1 KM (|(.! OalaSeM.xtd

, 7-7. Edit Relation


Edit Relation DataRelation.
DataTable DataColumn. ,
UpdateRule, DeleteRule AcceptRejectRule ForeignKeyConstraint. DataRelation.
ForeignKeyConstraint DataRelation , Foreign Key Constraint Only.
. XML Schema Designer
DataRelation :
DataTable (. 7-9).

III : DataSet ADO.NET

280

define -Atiorship (toyref), select etemert and Vey, selt th9 cMd element,
nd rher. *elKt*ta child * <[* each potent field.

Data* Properties

" * toy conrtralnt a

. 7-8. DataRelation
Edit Relation

Eto

E*

.**

&*

e*ug

5|

Sindm*

l! -

- S' ? .S- fe ^

tttp

eljijo
PtdpHfei

fbjitmrieriorderi

" >- ;-i. .":.jslo.n


L'

intKtrtle
Idress

iriq

11114
fl-jng

ftOdsrint

*[

t
^
F.
f.

CustometlD
EmployeelD
OrderM-RgqumdCut

ttrmg
in[
ditaTi
datsTir

-'s:keyrff>^3j JjJ

j| ComtrerttJa

nfar
fsiiactor "
JBdatfRule

mstns:keyl
./,'mn.*Jrder
(Dsfault)

ddubngan-i
* >te [O

. 7-9-

DataRelation

DataRelation
DataSet
DataRelation DataSet . , DataSet
, Web-, -

281

DataTable DataColumn. DataRelation


.
DataSet
Relations Properties.
Relations Collection Editor (. 7-10).
'- Relation* Editor
Relation 1 Properties:
,

...

" " '.'

ggmowe j

Close

M'rT

. 7-10. DataRelation DataSet


Relations Collection Editor
Relations Collection Editor ,
DataRelation.
DataRelation Edit Relation (. 7-8).

DataRelation
, DataRelation . - ,
. - .

DataRelation
DataRelation .
DataRelation. . 7-1 DataRelation.
ChildColumns
CbildColumns , DataColumn
DataTable.
.

282

III : DataSet ADO.NET

7-1.

DataRelation
*11&

CbildColmnns

CbiidKeyConstraint


DataColumn
ForeignKeyConstraint

DataTable

DataSet

DataSet

,
-
FOREIGN KEY ,

.

DataSet, Dai'aRetation.


, DataSet XML
, .
UNIQUE *
: .
.

ExtendedProperties
Nested

Property/Collection
Boolean


DataColumn
ParentKeyConstraint UniqueConstraint

ParcntColumns

ParentTable

DataTable

RelationName

String

ChildKeyConstraint
ChildKeyConstraint ForeingKeyConstraint, DataRelation. DataRelation
, ChildKeyConstraint Nothing null,
. .
ChildTable
ChildTable DataTable. .
DataSet
DataSet DataSet, DataRelation. .
ExtendedProperties
DataRelation, DataSet, DataTable DataColumn, ExtendedProperties, .
Nested
Nested ! DataTable
DataSet XML- Data-

283

SetWriteXml. :) Data-Relation, .
Nested False ( ),
DataTable . , DataSet, , DataRelatton, DataTable:

DataTable
<Customers>
<CustomerID>ALFKK/CustomerID>
<CompanyName>Alfreds Futterkiste</CompanyNanie>
</Customers>
<Customers>
<CustomerID>ANATR</CustornerID>
<CompanyName>Ana Trujillo Emparedados helados</CompanyName>
</Customers>
<0rders>
<OrderID>10308</OrderID>
<CustomerID>ANATR</CustomerID>
</Orders>
<0rders>
<OrderID>10355</OrderID>
<CustomerID>AROUT</CustomerID>
</Orders>
True ADO.NET DataTable DataTable:
DataTable

<Customers>
<Custome rID>ALFKK/Custome r!D>
<CompanyName>Alfreds Futterkiste</CompanyName>
<0rders>
<OrderID>10643</OrderID>
<CustomerID>ALFKK/CustomerID>
</Orders>
<0rders>
<OrderID>10692</OrderID>
<CustomerID>ALFKI</CustomerID>
</Orders>
</Customers>
<Customers>
<CustomerID>ANATn</CustomerID>
<CompanyName>Ana Trujillo Emparedados helados</CompanyName>

284

III

: DataSet ADO.NET

<0rders>
<OrderID>10308</OrderID>
<CustomerID>ANATR</CustomerID>
</Orders>
<0rders>
<OrderID>10625</OrderID>
<Custome rID>ANATR</Custome rlD>
</Orders>

</Customers>

ParentColumns
ParentColumns , DataColumn
DataTable.
,
ParentKeyConstraint
ParentKeyConstraint UniqueConstraint, DataRelation. DataRelation
, ParentKeyConstraint Nothing null . ,
ParentTable
ParentTable
DataTable. .
RelationName
RelationName ,
DataRelation.

,
.

DataRelation ?

. ,
Web-. , .
DataRelation,
.
DataSet . ?
, .
,
ADO.NET .
. , . ,
, -

285

.
?
. - Microsoft ,NET Framework
, . , . ,
, .
Visual Basic .NET, ADO.NET,
Visual Basic, ADO 2.6. Customers, Orders Order Details Northwind ,
. ,
.
, ,
DataTable, . :

,
SELECT C.CustomerlD, .CompanyName, ,ContactName, .Phone,
O.OrderlD, O.EmployeelD, Q.OrderDate,
D.ProductID, D.Quantity, D.UnitPrlce
FROM [Order Details] D, Orders 0, Customers
WHERE D.OrderlD = O.OrderlD AND O.CustomerlD = C.CustomerlD
AND C.Country = N'USA'


SELECT CustomerlD, CompanyName, ContactName, Phone
FROM Customers WHERE C.Country = N'USA'
SELECT O.OrderlD, 0.CustomerlD, 0.EmployeelD, O.OrderOate
FROM Orders 0, Customers
WHERE O.CustomerlD = C.CustomerlD AND C.Country = N'USA'
SELECT D.OrderlD, D.ProductID, D.Quantity, D.UnitPrice
FROM [Order Details] D, Orders 0, Customers
WHERE D.OrderlD = O.OrderlD AND O.CustomerlD = C.CustomerlD
AND C.Country = N'USA'


SELECT CustomerlD, CompanyName, ContactName, Phone
FROM Customers WHERE C.Country = N'USA 1
SELECT OrderlD, CustomerlD, EmployeelD, OrderDate
FROM Orders WHERE CustomerlD = ?
SELECT OrderlD, ProductID, Quantity, UnitPrice
FROM [Order Details] WHERE OrderlD = ?

286

III

: DataSel ADO.NET

, , . , , . ,
. , 20% 6-8 .
? , , , , .
, , . , Order
Details 100 ,
Customers, .
WriteXml DataSet ( 12) DataSet XML-. XML-, DataSet ,
XML-, DataSet . , ,
, .

Customers DataTable,
Orders.
Orders
Order Details. . , , .
.
,
, ,

, ,
.
, IN,
. IN
, . ,
8%.
. , , ,
. *
DataTable?

287

. ADO.NET :
. , DalaReader Find Rows DataTable (
).
Customers Order Details. DataReader
DataTable Customers
Orders.
Visual Basic .NET
ds.Tables("Customers")-BegtnLoadData)
ds,Tables("Orders").BeginLoadData{)
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetS[>K;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim on As New OleDbConnection(strConn)
en.Openf)
strSQL = "SELECT C.CustomerlD, C.CompanyName, C.ContactName, " i
"C.Phone, O.OrderlD, O.EmployeelD, O.OrderDate " & _
"FROM Customers C, Orders 0 " & _
"WHERE C.CustomerlD = O.CustomerlD AND C.Country = 'Canada'"
Dim cmd As New 01eDbCommand{strSQL, en)
Dim rdr As OleDbDataReader = cmd.ExecuteReader
Dim objNewCustomer, objNewOrder As Object()
Do While rdr.Read
If ds.Tables("Customers").Rows.Find(rdr.GetString{0)> Is Nothing Then
objNewCustomer = New ObjectO {rdr.GetString(O),
rdr.GetString(l),
rdr,GetString(2),
rdr.GetStringO)}
ds.Tablesf"Customers").LoadDataRow(objNewCustomer, True)
End If
objNewOrder = New Object{) {rdr.Get!nt32(4),
rdr.GetString(O),
rdr.Gent32(5),
rdr.6etDateTime(6)}
ds.TablesC"Orders").LoadDataRow(objNewOrder, True)
Loop
rdr.Close()
cn.CloseO
ds.Tables("Customers").EndLoadDataf)
ds.TablesC"Orders"). EndLoadDataQ

Visual C# .NET
ds.Tables["Customsrs"].BeginLoadData();
ds.Tables["Orders"].BeginLoadData();
string strConn, strSQL;
StrConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";

288

111 : DataSet ADO.NET

OleDbConnection en = new 01eDbConnection{strConn);


cn.OpenO;
strSQL = "SELECT C,CustomerlD, C.CompanyName, C.ContactName, " +
"C.Phone, O.OrderlD, 0.EmployeelD, O.OrderDate " +
"FROM Customers C, Orders 0 " +
"WHERE C.CustomerlD = 0.CustomerlD AND C.Country = 'Canada'";
QleDbCommand cmd = new 01eDbCommand(strSQL, en);
OleDbDataReader rdr = cmd. ExecuteReaderO;
obj ect[] objNewCustomer, obj NewOrde r;
while (rdr.ReadO)
(
if (ds.Tables["Customers"].Rows.Find(rdr.GetString(0)) == null)
<
objNewCustomer = new object[] (rdr.GetString(O),
rdr.GetString{1),
rdr.GetString{2),
rdr.GetString(3)};
ds.Tables["Customers"].LoadDataRow(objNewCustomer, true);
}
objNewOrder = new object[] {rdr.Get!nt32(4),
rdr.GetString(O),
rdr.Get!nt32(5),
rdr.GetDateTime(6)};
ds.Tables["Orders"].LoadDataRow(ob]NewOrder, true);
!
rdr.CloseO;
cn.Close{);

ds. Tablest"Customers"].EndLoadData();
ds.Tablest"Orders"].EndLoadData{);

8
, ,

> 5 , DataAdapter DataSet. , DataSet , , DataRow DataTable.


DataTable ? , , ? , ?
, Fmrf DataRowCollection, Select DataTable
DataVieiv DataRowVieiv.


DataTable
DataTable . . Find,
. , Select, , , .


, , :

290

III

: DataSel ADO.NET

SELECT CustomerlD, CompanyName, ContactName, Phone


FROM Customers WHERE CustomerlD = 'ALFKI'

DataRow DataTable . , , 7 , DataTable. Find


DataTable .
, Find DataTable, DataRowCollection. Find ,
.
, Find DataRow. ,
.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;uata Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone " & _
"FROM Customers"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim tbl As New DataTableO
da.Fill(tbl)
tbl.PrimaryKey = New DataColumn() {tbl.Columns("CustomerID")}
Dim row As DataRow = tbl.Rows.Find("ALFKI")
If row Is Nothing Then
Console.WriteLine("Row not found!")
Else
Console.WriteLine(row("CompanyName"))
End If

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone " +
"FROM Customers";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
DataTable tbl = new DataTableO;
da.Fill(tbl);
tbl.PrimaryKey = new DataColumn[] {tbl.Columns["CustomerID"]};
DataRow row = tbl.Rows.FindC'ALFKI");
if (row == null)
Console.WriteLine("Row not found!");
else
Console.WriteLine(row["CompanyName"]);

, ,

291

, DataTable .
EnforceConstraints DataSet False, PRIMARY KEY DataTable . Find
.
Find ,
DataTable DataColumn. , Order Details OrderlD ProductlD.
DataTable
:
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, ProductlD, Quantity, UnitPrice " & _
"FROM [Order Details]"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim tbl As New DataTable(>
da.Fill(tbl)
tbl.PrimaryKey = New DataColumnQ {tbl.Columns("OrderID"),
tbl.Colunns("ProductlD")}
Dim objCriteria As New Objectf) {10643, 28}
Dim row As DataRow = tbl.Rows.Find(objCriteria)
If row Is Nothing Then
Console.WriteLine("Row not found!")
Else
Console.WriteLine(row("Quantity") & " - " & row("UnitPrice"))
End If

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT OrderlD, ProOuctID, Quantity, UnitPrice " +
"FROM [Order Details]";
OleObOataAdapter da = new QleDbDataAdapter(strSQL, strConn);
DataTable tbl = new DataTableO;
da.Fill(tbl);
tbl.PrimaryKey = new DataColumn[] {tbl.Columns["OrderID"],
tbl.Columnst"ProductlD"]};
object[] objCriteria = new object[] {10643, 28};
DataRow row = tbl.Rows.Find(objCriteria);
if {row == null)

292

III : DataSet ADO.NET


Console.WrlteLlne("Row not found!");

else

Console.WriteLine(row["Quantity"] + " - " + row["UnitPrice"]);


,
. , (USA), (Seattle)?
WHERE:
SELECT CustomerlD, CompanyName, ContactName, Phone, City, Country
FROM Customers WHERE Country = 'USA' AND City <> 'Seattle'

Select DataTable .
, Customers DataTable,
. , :
Visual Basic .NET
Dim strConn, strSQL. As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT CustomerlD, CompanyName, ContactName, " & _
"Phone, City, Country FROM Customers"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim tbl As New DataTableO
da.Fill(tbl)
Dim aRows As DataRowO
Dim row As DataRow
aRows = tbl.Select("Country = 'USA' AND City <> 'Seattle'")
For Each row In aRows
Console.WriteLine(row("CompanyName") & " " & rowf'City") i
" - " & rowC'Country"))
Next row

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind; Trusted_Connection-Yes;";
strSQL = "SELECT CustomerlD, CompanyName, ContactName, " +
"Phone, City, Country FROM Customers";
OleDbDataAdapter da = new 01edbDataAdapter(strSQL, strConn);
DataTable tbl = new DataTableO;
da.FIll(tbl);
DataRow[] aRows = tbl.SelectC'Country = 'USA' AND City <> 'Seattle'");
foreach (DataRow row in aRows)

8 , ,

293

Console.WriteLine(row["CompanyName"] + " - " + row["Clty"] +


" - " + row["Country"]);


ADO.NET . SQL-
, CustomerlD .
SELECT CustomerlD, CompanyNante, ContactName, Phone
FROM Customers WHERE CustomerlD LIKE '

% *.
, - (New Hampshire),
- (New Jersey), - (New Mexico) - (New York):
strFilter = "State LIKE 'New %'"

(Dakota):
strFilter = "State LIKE 'K Dakota" 1
? _ ADO.NET .

-
, , , ,
DataTable,Select .
.
, .
. , - , . , O'Malley.
, :
LastName = 'O'Malley'

, -,
. :
LastName = ' 0 ' ' M a l l e y 1

, -.
Replace String.
Select Replace String :

Visual Basic .NET


strCriteria = "LastName = '" & strLastName.Replacef

) & "'"

294

III

: DalaSet ADO.NET

Visual C# .NET
strCriteria = "LastName = ' " + strLastName.Replace("'",

) +

? *,
( , - ).
strCriteria = "OrderDate >= 01/01/2002 AND OrderDate < 02/01/2002"

- , , ,
, -,
SUM. , Space In Name
, Space In Name 3,
:
strCriteria = "[Space In Name] = 3"

. -?
- (]) (\).
, Bad]Column[Name
, Bad]Column[Name 5,
:

Visual Basic .NET


strCriteria = "[Bad\]Column[Name] = 5"

Visual C# .NET
strCriteria = "[Bad\\]Colunin[Name] = 5";

, * \ . strCriteriaFilter

"[Bad\]Column[Name] = 5"

, - ,
, - . DataTable
, .
, .

Visual Basic .NET


Dim tbl As New DataTableQ
tbl.Columns.Add("ID", GetType(Integer))
tbl.Columns.Add("Why]would[you ever\use.thistfcolumn/name?",
GetType(String))
tbl.LoadDataRow(New Object{) {1, "Thompson"), True)
tbl.LoabDataRow(New ObjectO {2, "O'Halley"}, True)

8 , ,

295

Dim strFilter, strFieldName, strValue As String


Dim row As DataRow

strFieldName = "Why]would[you ever\use.thisftcolumn/name?"


strValue = "O'Malley"
strFilter = "[" & strFieldName.ReplaceC"]", "\]") &
"] = '" & strValue.Replacef
,
}&
For Each row In tbl.Select(strFilter)
Console.WriteLine(row(strFieldName))
Next row
Visual C# .NET
DataTable tbl = new DataTableO;
tbl.Columns.Add("ID", typeof(int;
tbl.Columns.Add("Why]would[you ever\\use.thisftcolumn/name?'
typeof(string));
tbl.LoadDataRow(new object[] {1, "Thompson"}, true);
tbl.LoadDataRow(new object[] {2, "O'Malley"}, true);
string strFilter, strFieldName, strValue;
strFieldName = "Why]would[you ever\\use.this#column/name?";
strValue = "O'Halley";
strFilter = "[" + StrFieldName.ReplaceC"]", "\\]") +
"] = ' " + strValue.Replace(
) +
;
foreach (DataRow row in tbl.Select(strFilter))
Console.WriteLine(row[strFieldName]);
, , : - .

Select
ADO.NET, Select .
, , , (, ).
.

, Select,
DataTable , . DataRow, Select, .
SQL- , ,
ORDER BY. , , City:

296

III

: DataSet ADO.NET

SELECT CustomsrID, CompanyName, ContactName, Phone, City


FROM Customers ORDER BY City

ORDER BY
City ORDER BY City DESC.
Select, OltDER BY SQL-,
.
DataRow, Select,
City.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEOB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection~Yes;"
strSQL = "SELECT CustomerlD, CompanyName, ContactName, " &
"Phone, City, Country FROM Customers"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim tbl As New DataTableO
da.FiU(tbl)
strCriteria As String = "Country = 'USA' AND City <> 'Seattle'11
strSortQrder As String = "City DESC"
aRows As DataRow() = tbl.Select(strCriteria, strSortOrder)
row As DataRow
Each row In aRows
Console.WriteLine(row("CompanyName") & " - " & row("City") 4 _
" - " & row("Country"
Next row
Dim
Dim
Dim
Dim
For

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT CustomerlD, CompanyName, ContactName, " +
"Phone, City, Country FROM Customers";
OleDbDataAdapter da = new OleDbDataAdapterfstrSQL, strConn);
DataTable tbl = new DataTableO;
da.Fill(tbl);
string strCriteria = "Country = 'USA' AND City <> 'Seattle'";
string strSortOrder = "City DESC";
Dataflow[] aRows = tbl.Select(strCriteria, strSortOrder);
foreach (DataRow row in aRows)
Console.WriteLine(row["CompanyName"] + " - " + row["City"] +
" - " + row["Country"]);

, DataSet . , DataTable'!

8 , ,

297

Select DataViewRoivState. , , . , DataTable. ModifiedOriginal Deleted DataViewRoivState :


Visual Basic .NET
Dim dvrs As DataViewRowState
dvrs = OataViewRowState.ModifiedOriginal Or DataViewRowState.Deleted
Dim aRows As DataflowO = tbl.Select("", "", dvrs)
Dim row As Dataflow
For Each row In aRows
Console.WriteLine(row("CompanyName", DataRowVersion.Original))
Next row

Visual C# .NET
DataViewRowState dvrs;
dvrs = DataViewRowState.ModifiedOriginal | DataViewRowState.Deleted;
DataRow[] aRows = tt)l.Select("", "", dvrs);
foreach (DataRow row in aRows)
Console.WriteLine(row["CompanyNanie", DataRowVersion.Original]);
, .

DataView
Select DataTable , , ,
.
. -, Select
. -, Windows- Web- Select DataRow. ADO.NET ,
, DataView.
DataTable ADO.NET , , . DataView , , DataTable ,
*
DataView DataTable
DataVieu1 .
DataView ,
DataTable.
.
, .

1-595

298

III : DataSel ADO.NET

DataView SQL-
. ,
, :
CREATE VIEW ViewCustomersAndOrders AS
SELECT C.CustomerlD, C.CompanyName, C.ContactName, C.Phone.
O.OrderlD, 0,EmployeelD, O.OrderDate
FROM Customers C, Orders 0 WHERE C.CustomerlD = 0.CustonerlD
DataView ADO.NET ,
DataTable, SQL-. DataView DataTable, DataTable.
DataView ,
DataTable; ,
DataView DataTable.
DataRelation
DataRelation , , , , DataTable
,
DataTable
DataColumn,
DataTable :

Visual Basic .NET


ds.Relations.Add("CustomersOrde rs",
ds.Tables{"Customers").Colunms("Customer-ID"), _'

ds.Tables("Orders")-CDiuitins("CustoifierID"))
tfs.Tab!es{"Orders").Columns.Add("CompanyName", GetTypsfString), _
"Pa rent(CustomersQrders).CompanyName"}

Visual C# .NET
ds.Relations.Add("CustomersQniers",
ds,Tables["Customers"3.Colufflns["Cu8tomerID"3,
ds.TablesE"Orders"].ColumnsE"CustoiRerID"3);
ds.Tables["Orders"].Columns.Adtf("CompanyName", typeof(string),
"Parent (Customs rsOrders).CoiapanyNaiiie");

DataView
DataView ,
Select DataTable.
Select.

8 , ,

299

DataView
DataView DataTable,
DataTable. DataTable, DataView: Table DataView . :
Visual Basic .NET
Dim tbl As New 1("")
Dim vue As DataView
vue = New DataView()
vue.Table = tbl
vue = New DataView(tbl)
Visual C# .NET
DataTable tbl = new DataTable("HMaTa6rHu.bT);
DataView vue;
vue = new DataView();
vue.Table = tbl;
vue = new DataView(tbl);

Table DataVieiv DataTable, TableName DataTable ( ). , DataVieiv


DataTable ,
DataView , Select DataTable. Table, RowFilter, Sort RowStateFilter DataVieit'
. :
Visual Basic .NET
Dim tbl As New DataTableC'Customers")
Dim dvrs As DataViewRowState
dvrs = DataViewRowState.ModifiedOriginal Or DataViewflowState.Deleted
Dim vue As DataView
vue = New DataView
vue.Table = tbl
vue.RowFilter = "Country = 'USA'"
vue.Sort = "City DESC"

vue.RowStateFilter = dvrs
vue = New DataView(tbl, "Country = ' U S A ' " , "City DESC", dvrs)

300

111 : DataSet ADO.NET

Visual C# .NET
DataTable tbl = new DataTable("Customers"};
DataViewRowState dvrs;
dvrs = DataViewRowState,ModifiedOriginal Or DataViewRowState.Deleted;
DataView vue;
vue = new DataView;

vue.Table = tbl;
vue.RowFilter = "Country = 'USA'";
vue.Sort = "City DESC";
vue.RowStateFilter = dvrs;
vue = new DataView(tbl, "Country = 'USA'", "City DESC", dvrs};

RowStateFilter
RowStateFilter DataViewRowState
(. 8-1).
RowState DataRow DataRowVersion.
RowStateFilter . ,
ModifiedOriginal, DataView
, .
8-1.

Added
CurrentRows
Deleted
ModifiedCurrent
ModifiedOriginal
None
OriginalRows
Unchanged

DataViewRowState


, (
)




,

,

DataRowView
Select DataTable ModifiedOriginal, . ,
, Select,
DataRow - ,
,
DataView ,
DataVieiv DataRowView. DataRowView DataRow. , DataRowView

8 , ,

301

Item,
, . Item , DataRowView
, DataRowVersion .
DataView
DataRoivView DataRowView
:
Visual Basic .NET
Dim tbl As New DataTable("Customers")
Dim vue As DataView
vue = New DataView(tbl)
Dim row As DataRowView = vue(O)
Console.WriteLine{vue("CompanyName")}
Visual C# .NET
DataTable tbl = new DataTable("Customers");
DataView vue;
vue = new DataView(tbl);
DataRowView row = vue[0];
Console.WriteLlne(vue["CompanyName"]);

DataRowView , Row DataRow,

,
DataView
DataTable DataView
, DataTable. DataTable Rows,
For Each. DataView , ,
.
DataTable Count, ,
DataVieic. ,
For .
, DataTable GetEnumerator,
lEnumerator. , System.Collections, ,
MoveNext DataReader.
, DataView Count GetEnumerator.

302

III

: DataSet ADO. NET

Visual Basic .NET


Dim tbl As New DataTable("Customers")
' DataTable
' OataView,
'
Dim vue As DataView
vue = New DataView(tbl, "", "", DataViewRowState.ModifieclQriginal)
Dim row As DataRowView
' DataView for
Dim intCounter As Integer
For intCounter = 0 To vue. Count - 1
row = vue(intCounter)
Console. WriteLine(row("CompanyName"))
Next intCounter
' DataView, GetEnumerator
Dim objEnum As lEnumerator = vue. GetEnumerator
Do While objEnum. MoveNextf)
row = CType(objEnum. Current, DataRowView)
Console . WriteLine( row( "CompanyName" ) )
Loop

Visual C# .NET
DataTable tbl = new DataTable("Customers");
// DataTable
// DataView,
//
DataView vue;
vue = new DataView(tbl, "", "", DataViewRowState.ModifiedOriginal);
DataRowView row;
// DataView for
for (int intCounter = 0; intCounter < vue. Count; intCounl:er++)
{
row = vue[intCounter];
Console.WriteLine(row["CompanyName"]);
// DataView, GetEnumerator
lEnumerator objEnum = vue.GetEnumerator();
while (objEnum.MoveNextO)
\
row = (DataRowView} objEnum. Current;
Console . WriteLine( row[ "CompanyName" ]);
!

8 , ,

303

DataView
, RowFilterwRowStateFilter
DataView. , DataView Find
FindRows, . Find
Row DataTable,
Find
Sort DataView, Find , ! (
Sort. Find DataRowCollection, DataView
,
Find Dait&iew DataRow
DataRowVieu.', integer,
DataView. , Find -1.
Find DataView
ContactName. , , Find .
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB;Data Source={local}\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim strSQL As String = "SELECT CustomerlD, CompanyName, ContactName, " &
"Phone, City, Country FROM Customers"
Dim da As New 01eObDataAdapter(strSQL, strConn)
Dim tbl As New DataTable("Customers")
da.Fill(tbl)
Dim vue As New DataView(tbl)
vue.Sort = "ContactName"
Dim intlndex As Integer = vue.Find("Fran Wilson")
If intlndex = -1 Then
Console.WriteLine("How not found!"}
Else
Console,WriteLine(vue(intlndex)("CompanyName"))
End If

Visual C# .NET
string strConn = "Provider=SQLOLEDB; Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
string strSQL = "SELECT CustomerlD, CompanyName, ContactName, " +
"Phone, City, Country FROM Customers";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn};
DataTable tbl = new DataTable("Customers"};
da.Fill(tbl);
DataView vue = new DataView(tbl);
vue.Sort = "ContactName";

304

111

: DataSet ADO.NET

Int intlndex = vue.Find("Fran Wilson");


if (intlndex == -1)
Console.WriteLineC"Row not found!");
else
Console,WriteLine(vue[intlndex]["CompanyName"]);

FindRows
Find DataRowCollection , PrimaryKey ( ) DataTable.
UNIQUE KEY, , Find DataRowCollection.
Find DataView ,
Sort . ,
DataView. , Country
Spain (). Find , .
, DataView FindRows. , Find DataView, FindRows DataRowView, ,
.
, FindRows :
Visual Basic .NET
Dim vue As New DataView(tbl)
vue.Sort = "Country"
Dim aRows As DataRowViewf) = vue.FindRows("Spain")
If aRows.Length = 0 Then
Console.WriteLine("No rows found!")
Else
Dim row As DataRowView
For Each row In aRows
Console.WriteLine(row("City"))
Next row
End If

Visual C# .NET
DataView vue = new DataView(tbl);
vue.Sort = "Country";
DataRowView[] aRows = vue.FindRowsf"Spain");
if (aRows.Length == 0)
Console.WriteLineC"No rows found!");

, ,

305

else
foreach (DataRowView row in aRows)
Console.WriteLine(row["City"]);

DataRowView
DataRoivVieiv DataRow. DataRowView, DataRow,
BeginEdit, EndEdit, CancelEdit Delete.
DataRowView
DataRow. DataView
AddNew, DataRowView. DataTable EndEdit
DataRowView.
, DataRowView , :
Visual Basic .NET
Dim tbl As New DataTable("Customers")
Dim vue As New DataView(tbl)
'
Dim row As DataRowView = vue.AddNew()
row("CustomerID") = "ABCDE"
rowC'CompanyName") = "New Company"
row("ContactName") = "New Contact"
row("Phone") = "(617) 555-1212"
row.EndEditO
'
row. BeginEditO
rowC'CompanyName") = "Modified"
row.EndEditO
'
row.DeleteO

Visual C# .NET
DataTable tbl = new DataTableC'Customers");
DataView vue = new DataView(tbl);
//
DataRowView row = vue.AddNewO;
row["CustomerID"] = "ABCDE";
row["CompanyName"] = "New Company";
row["ContactName"] = "New Contact";
rowfPhone"] = "(617) 555-1212";

306

III

: DataSet ADO.NET

row.EndEdit();

//
row. BeginEditO;
row["CompanyName"] = "Modified"
row.EndEdit();
//
row.Delete();

DataView Visual Studio .NET


DataVieu' , DataTable. DataView
DalaTable (Rou'Filter, RoivStaleFilter, Sort ..).

DataView
DataView , DataView Data Visual Studio .NET .
DataView .

DataView
DataView
. Visual Studio .NET . Properties
(. 8-1) DataTable, DataVieic, RowFilter, RowStateFilter Sort.

Forml.vb [Deflfin j

. 8-1. DataView Visual Studio .NET

8 , ,

307

, , .

DataView
DataView,
.


. 8-2 DataView.
8-2.

DataView

AllotvDelete

Boolean

,
DataView

AllowEdit

Boolean

,
DataVieii'

AlloivNeu-

Boolean

,
DataView

ApplyDefaultSort

Boolean

,
( )

Count

Integer

DataVieiv
( )

DataView'Manager

DataViewManagei


DataViewManager DataView (
)

Item

DataRowVieu

DalaRowView, ,
DataVieic ( )

RowFilter

String

, ,
DataTable DataView. WHERE SQL-

RowStateFilter

DataViewRowState

,
DataView.

Sort

String

, DataView

Table

DataTable

DataTable,
DataView

AllowDelete, AllowEdit Allow/New

DataView
. AllowDelete, AllowEdit AllowNeiv
, . , DataView.
True,

308

III : DataSet ADO.NET

ApplyDefaultSort
ApplyDefaultSort False. True, DataVieu- DataTable, DataVieiv. ,
ApplyDefaultSort True, Sort DataView , DataTable. , DataView
DataTable, OrderlD ProduccID,
ApplyDefaultSort True Sort DataView
OrderlD, ProductlD.
Count Item
Item DataRouView.
Item, , .
Count , DataView.
DataView Count Item:

Visual Basic .NET


Dim tbl As New DataTable("Customers")
' DataTable
' DataView,
'
Dim vue As DataView
vue = New DataView(tbl)
Dim row As DataRowView
' For DataView
Dim intCounter As Integer
For intCounter = 0 To vue.Count - 1
row = vue(intCounter)
Console.WriteLine(row("CompanyName"))
Next intCounter
Visual C# .NET
DataTable tbl = new DataTable("Customers");
// DataTable
// DataView,
//
DataView vue;
vue = new DataView(tbl);
DataRowView row;
// For DataView
for (int intCounter = 0; intCounter < vue.Count; intCounter++)

8 , ,

309

row = vue[intCounter];
Console. WriteLine(row["CompanyName"]);

DataViewManager
DataView CreateDataView
DataViewManager, DataViewManager DataViewManager, DataView. DataViewManager.
DataViewManager ,
* .
RowFilter
RowFilter WHERE SQL-.
, . RowFilter .
:
vue. RowFilter = "Country = 'Spain'"
( , CustomerlD
):
vue. RowFilter = "CustomerlD LIKE "AM" 1
-:
vue. RowFilter = "OrderDate >= #01/01/2002 AND OrderDate < 02/01/2002"
- -
:
vue. RowFilter = "[Spaces In Column Name] = 'Op'Malley'"
RowStateFilter
RowStateFilter , DataView. DataRow
Rou'State, , DataView.
, RowStateFilter
DataViewRowState.
RowStateFilter, DataView.
RowStateFilter CurrentRows.
DataTable, , Sort DataView, .

310

III : DataSet ADO. NET

Sort
Sort ,
DataView, ORDER BY SQL-. . .
. DESC.
, - (, ),
, .
(Country, City):
vue.Sort = "Country, City"
:
vue.Sort = "OrderDate DESC"
-:
vue.Sort = "[Space In ColumnName]"

Sort ; DataView ,
DataTable. Sort DataView,
Table
Table DataTable,
DataView. Table, RowFilter
RowStateFtiter DataView .
Table, DataView.
Table
DataTable, TableNatne ;
.

DataView
DataView . 8-3.
8-3.

Beginlnit

DataView

DataRoicView

Delete

DataRowView

Endlnit

DataView

Find

DataView /ui

8 , ,

FindRows
GetEnumerator

311

DataView
lEnumeralor , DataView

AddNew Delete
AddNew Delete DataTable. AddNew DataRowView.
, EndEdit DataRowView
DataTable.
Delete DataView . DataRow DataRowView, Delete . , .
DataTable, Mtro^AcceptCbanges ( DataRow, DataTable DataSet, )
DataAdapter.
Beginlnit Endtnit
DataView,
,
, , Beginlnit Endlnit,
, , DataView
DataTable RowFilter DataView , .
DataView DataGrid Windows-, Table RowFilter DataView. , DataView, Beginlnit Endlnit DataView,
DataGrid
DataTable,

DataView .
Art-ay DataRowView, DataView. .
, , , RDO
ADO, , GetRows,
. , .
, , DataRowView. , ,
, - . , , , .
.

312

III : DataSet ADO.NET

Visual Basic .NET


Dim tbl As New DataTable("Customers")
Dim viie As DataView
vue = New DataView(tbl)
Dim aRows As DataRowVlew()
aRows-= Array.CreateInstance(GetType(DataRowView), vue.Count)
vue,CopyTo(aflows, 0)

Visual C# .NET
DataTable tbl = new DataTable("Customers");
DataView vue;
vue = new DataView(tbl);
DataRowView[] aRows;
aRows = Array,CreateInstance(typeof(DataRowView), vue.Count);
vue.CopyTo(aRows, 0);
Find FindRows
Find FindRoivs DataView.
.
DataView , Sort:
Visual Basic .NET
Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Truste'd_Connection=Yes;"
Dim strSQL As String = "SELECT CustomerlD, CompanName, ContactName, " &
"Phone, City, Country FROM Customers"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim tbl As New OataTableC'Customers")
da.Fill(tbl)
Dim vue As New DataView(tbl)
Console.WriteLine("Use the Find method to locate a row " &
"based on the ContactName column")
vue.Sort = "ContactName"
Dim intlndex As Integer = vue.Find("Fran Wilson")
If intlndex = -1 Then
Console.WriteLine(vbTab & "Row not found!")
Else
Console.WriteLine(vbTab & vue(intIndex}("CompanyName"
End If
Console, WriteLineO
Console.WriteLineC'Use the FindRows method to locate rows " &
"based on the Country column")
vue.Sort = "Country"

8 , ,

313

Dim aRows As DataRowView() = vue.FindRows("Spain")


If aRows.Length = 0 Then
Console.WriteLine(vbTab & "No rows found!")
Else
Dim row As DataRowView
For Each row In aRows
Console.WriteLine(vbTab & row("City"))
Next row
End If

Visual C# .NET
string strConn = "Provider=SQLOLEDB;Data Source={local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
string strSQL = "SELECT CustomerlD, CompanyName, ContactNarne, " +
"Phone, City, Country FROM Customers";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
DataTable tbl = new DataTable("Customers");
da.Fill(tbl);
DataView vue = new DataView(tbl);
Console.WriteLine("Use the Find method to locate a row " +
"based on the ContactName column");
vue.Sort = "ContactName";
int intlndex = vue.Find("Fran Wilson");
if (intlndex == -1)
Console.WriteLine("\t" + "Row not found!");
else
Console.WriteLine("\t" + vue[intIndex]["CompanyName"]);
Console. WriteLineO;
Console.WrlteLine("Use the FindRows method to locate rows " +
"based on the Country column");
vue.Sort = "Country";
DataRowView[] aRows = vue.FindRows("Spain");
if (aRows.Length == 0)
Console.WriteLine("\t" + "No rows found!");
else
foreach (DataRowView row in aRows)
Console.WriteLine("\t" + row["City"]);
GetEnumerator
GetEnumerator
DataView. lEnumerator, System.Collections.
MoveNext lEnumerator Read DataReader
, ,
. Current
Object. DataRowVieir.

314

III

: DataSet ADO. NET

Visual Basic .NET


Dim tbl As New DataTable("Customers")
Dim vue As DataView(tbl)
Dim row As DataRowView
Dim objEnum As lEnumerator = vue.GetEnumerator
Do While objEnum.HoveNextO
row = CType(objEnum. Current, DataRowView)
Console. WriteLine( row( "CompanyName" ) )
Loop

Visual C# .NET
DataTable tbl = new DataTableC'Customers");
DataView vue = new DataView(tbl);
DataRowView row;
lEnumerator obJEnum = vue.GetEnumerator();
while (objEnum.MoveNextO)
t
row = (DataRowView) objEnum. Current;
Console . WriteLine( row[ "CompanyName" ] };

ListChanged DataView
DataView ListChanged, DataView, ,
, Data-View-, DataAdapter
DataTable; RowFtlter, RoivStateFilter, Sort Table DataView. :
Visual Basic .NET
Dim vue As New DataViewO
AddHandler vue, ListChanged, vue_ListChanged
Private Sub vue_ListChanged(ByVal sender As Object,
ByVal e As ListChangedEventArgs)
Console. WriteLine("ListChanged - " &
e. ListChangedType . ToSt ring ( ) )
End Sub
Visual C# .NET
// using System. ComponentModel
DataView vue = new DataView;
vue, ListChanged += new ListCnangedEventHandler(vue_ListChanged);
private void vue_ListChanged(object sender, ListChangedEventArgs e)

8 , ,

315

Console.WriteLine("ListChanged - " +
. ListChangedType.ToStringQ);

DataRowView
. 8-4 DataRowView;
.
8-4. DataRowView

DataView


DataView

IsEdit

Boolean

IsNew

Boolean

Item
Row

Object
DataRow

RowVersion

DataRowVersion

DataView,
DataRowView.
, .
, -
/
DataRowView
DataRow.
,
DataRow DataRowView.

DataView
DataView, DataRowView.
IsEdit IsNew
IsEdit IsNew ,
DataRowView, , .
( DataRowView
DataViewAddNew, EndEdit, DataTable), IsNew True, IsEdit
False. IsNew False, IsEdit True.
Item
Item DataRowView
DataRow. Item
DataRowView . Item .
Row
DataRowView DataRow. , DataRowView AcceptChanges GetCbanges.
DataRow, Row

316

III : DataSet ADO.NET

DataRoivView. DataRowView
DataRow.
RowVersion
DataRoivView
, Item,
RowVersion DataRowView.
RowVersion ,
DataRowVersion.

DataRowView
DataRoivView . 8-5.
8-5. DataRowView



DataView,


BeginEdit, CancelEdit EndEdit


BeginEdit, CancelEdit EndEdit DataRowView DataRow. BeginEdit,
EndEdit. CancelEdit.
CreateChildView
, DataView, , . , , DataView
. Table DataTable,
, RowFilter CustomerlD = 'ALFKI\
. , (CustomerlD) -?
, ?
DataRowView CreateChildView. DataRelation ( , GetChildRows
DataRow). CreateChildView DataView, .
, CreateCbildView-.

, ,

317

Visual Basic .NET


Dim ds As New DataSetO
Dim tblCustomers, tblOrders As DataTable
tblCustomers = ds.Tables("Customers")
tblOrders = ds,Tables("Orders")
ds,Relations.Add("CustomersOrders", tblCustomers.Columns{"CustomerID"),
tblOrders.Columns("CustomsrID"))
Dim vueCustomers, vueOrders As DataView
vueCustomers = New DataView(tblCustomers)
vueOrders = vueCustomers(0}.CreateChildView("CustomersOrders")
Visual C# .NET
DataSet ds = new DataSetO;
DataTable tblCustomers, tblOrders;
tblCustomers = ds,Tables["Customers"];
tblOrders = ds.Tables["Orders"];
ds.Relations.Add("CustomsrsOrders", tblCustomers.Columns["CustomerID"],
tblOrders.Columns["CustomerID"]);
DataView vueCustomers, vueOrders;
vueCustomers = new DataView(tblCustoiners);
vueOrders = vueCustomers[0].CreateChildView("CListoinersOrders");

DataView CreateCbildView RowFilter 1.


. ?
DataView , - *
.
Delete
Delete DataRowView . ,
, -
DataTable. DataTable,
AcceptChanges
DataAdapter.

,
.
DataTable?
. , . :

31 8

III : DataSet ADO.NET

DataTable Rows find;


, , DataView;
, , DataViewFind;
DataTable.Select,
. DataView . - , Visual Studio
.NET ?
. . DataView Visual
Studio .NET, . -,
DataView ,
. , ,
.
* Visual Studio .NET DataView,
. Properties, Visual Studio
.NET DataView. , DataTable . Visual Studio .NET
. , , - (. 8-2).
, ,
.

lhalPMiNMCiilt.

. 8-2. , Visual Studio .NET



.

DataViewManagert

. DataViewManager DataViewSetting,
DataView,
. , DataViewManager , DataView,
.

, ,

319

. DataView, , Sort ?
. ,
Windows-. , DataView.
, Windows-, .
, , DataView,
Country .
,
ContactName. . 8-3 .

. 8-3-

Country

. . 8-3
ContactName Aria Cruz, Country Brazil.
DataVieu;
. . DataTable. :
Select DataTable Find DataView.
.
DataView, Sort ContactName.
Find DataView. ,
DataRow Country, ,
:
Visual Basic .NET
Dim tbl As New DataTable("Customers")
Dim vueByCountry As New DataView(tbl)
vueByCountry.Sort = "Country"
Dim vueByContactName As New DataView(tbl)
vueByContactName.Sort = "ContactName"
Dim intlndexCountry, intlndexContactName As Integer

320

111

: DataSel ADO.NET

intlndexCountry = -1
IntlndexContactName = vueByContactName.Find("Aria Cruz")
Dim row As Dataflow = vueByContactName(intIndexContactNai?ie), Row
Dim strCountry As String = rowf'Country")

Visual C# .NET
DataTable tbl = new OataTable("Customers");
DataView vueByCountry = new DataView(tbl);
vueByCountry.Sort = "Country";
DataView vueByContactName = new DataView(tbl);
vueByContactName. Sort = "ContactName";
int intlndexCountry, intlndexContactName;
intlndexCountry = -1;
intlndexContactName = vueByContactName.Find("Aria Cruz");
Dataflow row = vueByContactName[intIndexContactName].Row;
sthing strCountry = row["Country"];

. .
Find DataView, Country . Country, .
Country , FindRows DataView. GetRows
DataRoivView.
, DataRowView
, FindRows , , .
DataView,
. , .
. 8-3 ,
Country.
DaiaViewFind ,
DataView, .
, (Country),
,
.
1'iiui DataView,
, DataView , Country . , ,
, . , ;
, , DataView .

Visual Basic .NET


Dim intStartingPoint As Integer = vueByCountry.Find(row("Country"))
Dim intCounter As Integer = intlndexStartingPolnt

8 , ,
Do

If vueByCountry(intCounter).Row Is row Then


intlndexCountry = intCounter
blnFound = True
Exit Do
End If
intCounter += 1
Loop While intCounter < vueByCountry.Count And _
vueByCountry(intCounter)("Country") = strCountry
If Not blnFound Then
intCounter = intlndexStartingPoint - 1
Do While intCounter >= 0 And
vueByCountry(intCounter)("Country") = strCountry
If vueByCountry(intCounter).Row Is row Then
intlndexCountry = intCounter
blnFound = True
Exit Do
End If
intCounter -= 1
Loop
End If
If blnFound Then
Console.WriteLine(vueByCountry(intIndexCountry)("CompanyNarne"})
Else
Console.WriteLineC'Not found!")
End If

Visual C# .NET
int intStartingPoint = vueByCountry.Find(row["Country"]);
while {intCounter < vueByCountry.Count i&
vueByCountry[intCounter]["Country"],EqualsCstrCountry))
{
if (vueByCountry[intCounter].Row == row)
{
intlndexCountry = intCounter;
blnFound = true;
break;
}
intCounter++;
i
if (IblnFound)
{
intCounter = intStartingPoint - 1;
while (intCounter >= 0 &&
vueByCountry[intCounter]["Country"].Equals(strCountry
{
if <vueByCountry[intCounter].Row == row)

321

322

III

: DataSet ADO.NET

intlndexCountry = tntCounter;
blnFound = true;
break;
)
intCounter-;
)

if (blnFound)
Console.WriteLine(vueByCountry[lntIndexCountry]["CompanyName"]);
else
Console.WriteLine("Not found!");

9
DataSet

DataSet. , DataSet , , Recordset ADO :

ADO.NET Visual Basic .NET


txtCompanyName.Text = ds.Tables("Customers").Rows(0)("CompanyName")

ADO.NET Visual C# .NET


txtCompanyName.Text = ds.Tables["Customers"].Rows[0]["CompanyName"];

ADO, DAO Visual Basic


txtCompanyName.Text = rs.Fields("CompanyName").Value

,
Visual Basic. .
, .
, Microsoft Visual Studio
,NET DataSet .
:

Visual Basic .NET


txtCompanyNafne.Text = ds.Customers(O). CompanyName

324

111 : DataSet ADO.NET

Visual C# .NET
txtCompanyName.Text = ds.Customers[0].CompanyName;

DataSet
DataSet . , DataSet ,
DataSet ,
. ,
DataTable DataRow
.

DataSet

DataSet ? . ,
.NET Framework SDK. , ,
, Visual Studio .NET
.


.NET Framework SDK
XML Schema Definition Tool,
XML- (.xsd-). Write XmlSchema DataSet. DataSet ,
WriteXmiSchema DataSet
6, DataSet
Visual Studio .NET, , Visual Studio .NET
.xsd. (, ,
) DataSet, , WriteXmlScbema DataSet.
WriteXmlScbema Stream, TextWriter, XmlWriter . DataSet
. Customers Orders Northwind. ,
DataSet , DataRelation,
DataTable.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" 4 _
"Initial Catalog=Northwind;Trusted_Ccmnection=Yes;"
Dim en As New QleDbConnection(strConn)
strSQL = "SELECT CustomerlD, CompanyName, ContactNaroe, Phone " &
"FROM Customers"
Dim daCustomers As New OleDbOataAdapterfstrSQL, en)
StrSQL = "SELECT OrderlD, CustomerlD, Employee!D, OrderDate " &

DataSet

325

"FROM Orders"
Dim daOrders As New 01eDbDataAdapter(strSQL, en)
Dim ds As New DataSetO
ds.DataSetName = "Chapter9"
cn.OpenO
daCustomers.FillSchema(ds, SchemaType.Source, "Customers")
daOrders.FillSchema(ds, SchemaType.Source, "Orders")
cn.CloseO
ds.Relations.Add("CustomersOrders",
ds.TablesC"Customers").Columns("CustomerlD"),
ds.TablesC"Orders").Columns("CustomerlD"))
ds.WriteXmlSchemaC"C:\Chapter9.XSD")

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SOLOLEDB;Data Source=(local)\\NetSDK; " +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone " +
"FROM Customers";
OleDbDataAdapter daCustomers = new 01eDbDataAdapter(strSQL, strConn);
StrSQL = "SELECT OrderlD, CustomerlD, EmployeelD, OrderDate " +
"FROM Orders";
OleDbDataAdapter daOrders = new 01eDbDataAdapter(strSQL, strConn);
DataSet ds = new DataSetO;
ds.DataSetName = "Chapters";
cn.OpenO;
daCustomers.FillSchema(ds, SchemaType.Source, "Customers");
daOrders.FillSchema(ds, SchemaType.Source, "Orders");
cn.CloseO;
ds.Relations.Add("CustomersOrders",
ds.Tables["Customers"].ColumnsC"CustomerlD"],
ds.Tables["Orders"].Columns["CustomerID"]);
ds.WriteXmlSchema<"C:\\Chapter9.XSD");

fillSchema DataAdapter. . .xsd- . -


DataSet, *, FittSchema .
XML Schema Definition Tool
XML Schema Definition Tool
XSD.exe, bin
XML- (.xsd- .xdr-). ,
(.dll) (.).
DataSet .xsd. XML Schema Definition Tool

326

III

: DataSet ADO.NET

. MS-DOS :

Visual Basic .NET


C:\>XSD Chapter9.XSD /d /1:VB

Visual C# .NET
C:\>XSD Chapters.XSD /0

, Start\
Programs\Accessories Command Prompt. Start, Run cmd.exe.
XSD.exe
bin .NET Framework
Path. ,
XML- .
XML-. ,
, , DataSet.
Visual Basic .NET ,
. Visual * .NET.
XML Schema Definition Tool .
.NET Framework SDK; , ,
XSD /?.

DataSet :

Visual Basic .NET


Dim ds As New Chapter9()

Visual C# .NET
Chapters ds = new Chapter9();

DataSetName
DataSet, .xsd-. ,
.xsd-, . DataSetName Chapter9', DataSet ,


DataSet Visual Studio .NET . -
, , MS-DOS.

DataSet

327

, , . DataSet, , DataTable
DataRelation.
Microsoft Windows .
Data Windows-
QleDbDataAdapter. Data Adapter Configuration Wizard
OleDbDataAdapter Northwind. Generate SQL Statement SQL-:
SELECT CustomerlD, CompanyName, ContactName, Phone FROM Customers
SELECT OrderlD, CustomerlD, EmployeelD, OrderDate FROM Orders


Generate Dataset. Generate DataSet (. 9-1).
DataSet. Chapter9; .
Generate Detaset
Generate dataset that Includes the specified tables.
Choose a dataset:
Existing
chapters

Choose which tabte() to add to the datasetc


V. Customers (QleDbDataAdapterl)
V Orders (OleDbDataAdapter 2)

Add this dataset to Che design*-.

. 9-1-

DataSet

DataSet DataSet
. DataSet, ,
, , , DataRelation.
.
Solution Explorer . XML Schema
Designer Orders Add\New Relation.
Edit Relation (. 9-2). , .
. , . .
DataSet
, , DataSet
Data .

328

III : DataSet ADO.NET

(Wine l lelatmst (Wyrtf), stlect the patent element and ksy,


wither, f*M ea^espondme to each parent ftsM,

. 9-2. DataRelation DataSet


DataSet , Visual
Studio .NET .
1. DataSet.
2. FillScbema DataAdapter, Generate Dataset.
DataSet,
3. WriteXmlScbema DataSet.
4. .xsd-.
5. XML Schema Definition Tool .xsd- DataSet .
6. .

?
DataSet ?
, Solution Explorer . . , Show All
Files ( ). , , .
DataSet (Chapter9.xsd) .
DataSet ; Chapter9.vb ter9.cs . .xsx; DataSet,
XML Schema Definition Tool.
. ,
DataSet. DataTable Customers
Orders, , DataTable.

DataSet

329

(CustomersDataTable OrdersDataTable) , ,
DataRow.
Visual Basic .NET
Dim ds As New Chapter9()
OleDbDataAdapten.Fill(ds)
Dim tblCustomers As Chapter9,CustomersDataTable = ds.Customers
Dim rowCustomer As Chapter9.CustomersRow = tblCustomers(O)
Visual C# .NET
Chapters ds = new Chapter9();
OleDbDataAdapterl.Fill(ds);
Chapter9.CustomersDataTable tblCustomers = ds.Customers;
Chapters,CustotnersRow rowCustomer = tblCustomers[0];

DataSet

DataSet ,
DataSet.
,
DataSet DataSet ,


, DataTable DataSet,
DataTable . New-^ DataTahle DataRow
. DataRow , ,
Visual Basic .NET
Dim ds As New Chapter9()
Dim tblCustomers As Chapter9.CustomersDataTable = ds.Customers
Dim rowCustomer As Chapter9.CustomersRow
rowCustomer = tblCustomers.NewCustomersRow{)
rowCustomer. CustonterlD = "ABCDE"
rowCustomer.CompanyName = "New Company"
rowCustomer.ContactName = "New Contact"
rowCustomer.Phone = "(800) 555-1212"
tblCustorners.AddCustofnersRow( rowCustomer)
'
Dim rowCustomer As DataRow = tblCustomers.NewRowQ
rowCustomerC'CustomerlD") = "ABCDE"
rowCustomer("CompanyName") = "New Company"
rowCustomerC'ContactName") = "New Contact"

(II

330

: DataSet ADO.NET

rowCustomer{"Phone") = "(800) 555-1212"


tblCustomers,Rows.Add(rowCustamer)

Visual C# .NET
Chapter9 ds = new Chapter9();
Chapter9.CustomersDataTable tblCustomers = ds.Customers;
Chapter9.CustomersRow rowCustomer = tblCustomers.NewCustomersRowf);
rowCustomer.CustomerlD = "ABCDE";
rowCustomer.CompanyName = "New Company";
rowCustomer.ContactName = "New Contact";
rowCustomer.Phone = "(800) 555-1212";
tblCustomers.AddCustomersRowfrowCustomer);
//
DataRow rowCustomer = tblCustomers.NewRowO;
rowCustomer["CustomerID"] = "ABCDE";
rowCustomer["CompanyNarce"] = "New Company";
rowCustomer["ContactName"] = "New Contact";
rowCustomer["Phone"] = "(800) 555-1212";
tblCustomers.Rows.Add(rowCustomer);

,
DataSet . Visual
Studio .NET , .
<-

&id

Debug

Took

Winikw

Help

" 3 H*FormijLoad"

End
End Cless

Sub

.,isM|
[sPhcneNu

. 9-3- DataSet
Visual Studio .NET
. 9-3 . ,
DataRow .
Visual Basic 5 , .

9 DataSet

331

, Visual Basic 6 ADO 2.x ,


. DataSet

.
Add DataRowCottection, &<>:
DataTable .
DataTable Customers
DataSet:
Visual Basic .NET
Dim ds As New Chapter9()
Dim tblCustomers As Chapter9.CustomersDataTable = ds.Customers
tblCustomers,AddCustomersRow("ABCDE", "New Company",
"New Contact", "(800) 555-1212")
'
tblCustorners.Rows.AddfNew ObjectO {"ABCDE", "New Company", _
"New Contact", "(800) 555-1212"})

Visual C# .NET
Chapter9 ds = new Chapter9();
Chapter9.CustomersDataTable tblCustomers = ds.Customers;
tblCustomers.AddCustomersRow("ABCDE", "New Company",
"New Contact", "(800) 555-1212");
//
tblCustomers.Rows,Add(new object[] {"ABCDE", "New Company",
"New Contact", "(BOO) 555-1212"});

IntelliSense ,
, . Visual
Studio .NET
,
.

DataSet Find Rows DataTahle.
Find , DataTable , . , Order Details North wind OrderlD ProductlD.
Data-Table, Find,
:
Visual Basic .NET
Dim tblDetails As DataTable
Dim rowDetail As DataRow
rowDetail = tblDetails.Find(New ObjectO {10245, 7}}

332

III : DataSet ADO.NET

Visual C# .NET
DataTable tblDetails;
DataRow rowDetail;
rowDetail = tblDetails.Find(new object[] (10245, 7}};
, . , . ,
, .
DataTable ,
DataTable DataSet
Find. DataSet DataTable, Order Details,
, :
Visual Basic .NET
Dim ds As New Chapter9()
Dim tblDetails As Chapters.Order_DetailsDataTable ds.Order_Details
Dim rowDetail As Chapters.Order_DetailsRow
rowDetail = tblDetails.FindByOrderIDProductID(10245, 7}
If rowCustomer Is Nothing Then
Console.WriteLinef'Row not found!")
Else
Console.WriteLineC'Found " & rowDetail.GrderlD & " - " & _
rowDetail.ProductID)

End If

Visual C# .NET
Chapter9 ds = new Chapter9();
Chapter9.0rder_DetailsDataTable tblDetails = ds.Order_Details;
Chapter9.0rder_DetailsRow rowDetail;
rowDetail = tblDetails.FindByOrderIDProductID(10245. 7);
tf (rowDetail == null)
Console.WriteLine("Row not found!");
else
Console.WriteLineC'Found " + rowDetail.OrderlD.ToStringO +
" + rowDetail. ProductlD.ToStringO);

DataSet
DataSet. BeginEdit, EndEdit CancelEdit. , DataRow, DataRow
:

9 DataSet

333

Visual Basic .NET


Dim ds As New Chapter9()
OleDbDataAdapterl.Fill(ds)
Dim rowCustomer As Chapter9.CustomersRow = ds.Customers(O)
rowCustomer.CompanyName = "Modified"
'
rowCustomerC'CompanyName") = "Modified"

Visual C# .NET
Chapter9 ds = new Chapter9();
OleDbDataAdapterl.Fill(ds);
Chapter9.CustomersRow rowCustomer = ds.Customers[0];
rowCustomer.CompanyName = "Modified";
//
rowCustomer["CompanyName"] = "Modified";
NULL
- Visual Studio .NET NULL. , NULL ,
. 6, IsNull DataRow NULL, System.ConverWBNutt
.
Dataset NULL. DataRow : , NULL, . . ContactName, IsContactNameNull SetContactNameNull.

Visual Basic .NET


Dim ds As New Chapter9()
OleDbDataAdapterl.Fill(ds)
Dim rowCustomer As Chapter9.CustomersRow = ds.Customers(O)
', ContactName Null
If rowCustomer.IsContactNameNullO Then
Console.WriteLinef"Contact name is Null")
Else
Console.WriteLine("Contact name: " & rowCustomer.ContactName)
End If
' ContactName Null
rowCustomer.SetContactNameNullO
'Instead of

334

III

: DataSet ADO.NET

If rowCustomer.IsNullC'ContactName") Then

'And
rowCustomerC'ContactName") = Convert.DBNull

Visual C# .NET
Chapter9 ds = new Chapter9();
OleDbDataAdapterl.Fill(ds);
Chapter9,CustomersRow rowCustomer = ds.Customers[0];
//, ContactName Null
if (rowCustomer. IsContactNameNullO) then
Console.WriteLine("Contact name is Null");
else
Console,WriteLine("Contact name: " + rowCustomer.ContactName);
// ContactName Null
rowCustomer. SetContactNameNullO;
//
if

(rowCustomer.IsNull("ContactName"))

//
rowCustomer["ContactName"] = Convert.DBNull;


DataRow
GetChildRows GetParentRow. DataRelation, , . DataSet
DataRelatiom, XML Schema
Definition Tool , DataRelation . DataSet
DataRelation, DataTable Customers Orders.
.xsd- DataSet, XML
Schema Definition Tool DataRou1 DataTable Customers
GetOrdersRows, DataRow DataTable Orders GetCustomersRows.
GetOrdersRows
.
Visual Basic .NET
Dim ds As New Chapter9{)
OleDbDataAdapterl.Fill(ds)
DleDbDataAdapter2,Fill(ds)
Dim rowCustomer As Chapter9.CustomersRow
Dim rowOrder As Cnapter9.0rdersRow
For Each rowCustomer In ds.Customers
Console.WriteLineC'Orders for " & rowCustomer.CompanyName)

9 DataSet

335

For Each rowOrder In rowCustomer.GetOrdersFlowsO


Console.WriteLine(vbTab & rowOrder.OrderlD &
" - " & rowOrder.OrderDate)
Next rowOrder
Next rowCustomer

'
Dim rowCustomer, rowOrder As Dataflow
For Each rowCustomer In ds.Tables("Customers").Rows
Console.WriteLine("Orders for " & rowCustomer("CompanyName"})
For Each rowOrder In rowCustomer.GetChildRowsC'CustomersOrders")

Visual C# .NET
Chapter9 ds = new Chapter9();
OleDbDataAdapterl . Fill(ds) ;
OleDbDataAdaptera. Fill(ds);
CustomersDataTable tblCustomers = ds. Customers;
CustomersRow rowCustomer = tblCustomers[0];
foreach (Chapter9. CustomersRow rowOrder
in ds.Tables[ "Customers"]. Rows)
{
Console. WriteLine("Orders for " + rowCustomer. CompanyName);
foreach (Chapter9.0rdersRow rowOrder
in rowCustomer. GetOrdersRowsO)
Console. Writeline("\t" + rowOrder. OrderlD. ToStringO +
" - " + rowOrder. OrderOate. ToStringO);

//
foreach (DataRow rowCustomer in ds,Tables["Customers"].Rows)
!
Console, WriteLine("Orders for " + rowCustomer["Co(npanyName"]>;
foreach (DataRow rowOrder in
rowCustomer. GetChildRowsC'CustomersOrders")}

DataSet, DataTable DataRow


, XML Schema Definition
Tool, DataSet. DataTable DataRow. ,
, .
, DataSet
/ XML- .
DataSet, ReadXml
WriteXml. ,
DataAdapter, DataSet
.

336

III

: DataSet ADO.NET

DataSet

, Microsoft , , DataSet
. DataSet .
, XML Schema Definition Tool,
DataSet
. ? ,
( , , ).

. ,
.
, , .
:
, . ,
, . - . , . , , .
: ,
. . , .
, , .
. , ,
, 12 ,
? .
. .
.
, ,
.
.
, .
, DataSet DataSet. ,
,
. ,
.

, DataSet , IntelliSense
Visual Studio .NET -

9 DataSet

337

DataSet , DataSet.
, ,
DataSet
DataTable, DataColumn, DataRelation Constraint.
DataSet : , .xsd- ReadXmlScbema DataSet FfflSc.be DataAdapter. ,
FillSchema ( ReadXmlSchema .xsd-). 5 , .
Windows- Web-,
, , DataSet .
? , Visual Studio
.NET ,
.
. 9-4 . DataRelation Customers-Orders,
, . :
DataTable Orders. ,
- .

. 9-4. DataSet

DataSet
. '
Web-, DataSet -

338

III

: DataSet ADO.NET

, .xsd- ,
DataSet . ,
- , DataSet ,

DataSet ? ?
DataSet
, .

DataSet DataSet :
Visual Basic .NET
'
Dim dsUntyped As New DataSetO
' DataSet
txtCompanyName.Text =
dsUntyped.Tables("Customers">.Rows{0)("CompanyName")
'Co
Dim dsTyped As New Chapter9()
' DataSet
txtCompanyName.Text = dsTyped,Customers(0).CompanyNanie
Visual C# .NET
//
DataSet dsUntyped = new DataSetO;
// DataSet
txtCompanyName.Text =
(string) dsUntyped.Tables["Customers"].Rows[0]["CompanyName"];
//Co
Chapter9 dsTyped = new Chapter9();
// DataSet.
txtCompanyName.Text = dsTyped.Customers[0].CompanyName;

. ? - Visual Studio .NET,


-
. ,

, DataSet,

DataSet

339

DataSet
? 6 , DataRow
,
DataColumn. ,
DataColumn, ,
.
, ,
, XML Schema Definition Tool,
. , , , , , DataColumn. . 9-5 ,
XML Schema Definition Tool , panyName Cusmoters.
, Visual Basic .NET, Visual Studio .NET,
* V,'iiir]t>wiiA|j|ilHMi)iin1

Mlcrovtlt Vfcujl li-itii Ml) [di'

chapter 9.<* {
p J Cull omeriRow (Windowiftpplli M Ic.n L tia(]ler9)

. 9-5- DataSet ,
CompanyName Customers
,
DataColumn:
Visual Basic .NET
Dim dsUntyped As New DataSet()
' OataSet
Dim tblCustomers As DataTable = dsUntyped.Tables(O)
'
Dim colCompanyName As DataColumn
colCompanyName = tblCustomers.Columns("CompanyName")
Dim row As DataRow = tblCustomers.Rows(O)
txtCompanyName.Text = CType(row(colConpanyName), String)

340

III : DataSet ADO.NET

Visual C# .NET
DataSet dsUntyped = new DataSetQ;
// DataSet
DataTable tblCustomers = dsUntyped.Tables[0];
//
DataColumn colCompanyName;
colCompanyName = tblCustomers.Columns["CompanyName"];
DataRow row = tblCustomers.Rows[0];
txtCompanyName.Text = (string) row[colCompanyName];

. DataSet
, . ,
DataSet , .
.
DataSet , DataSet , .
DataSet .
, , ,
DataSet ,
DataSet. , , DataColumn-.
, .
? , ,
DataSet, 510% , DataSet .
DataSet , ,
. DataSet ( 810% ),
DataSet .


DataSet . ,
, DataSet .

DataSet ,
DataColumn,
DataSet . ,
DataSet . DataSet , ,
, -

DataSet

341

. , ,
,
, , DataSet
DataSet .
DataSet
DataSet
DataSet, , DataSet
DataSet :
:
Visual Basic .NET
Dim dsStrong As Mew Chapter9()
Dim dsllntyped As DataSet
dsUntyped = CType(dsStrong, DataSet}

Visual C# .NET
Chapter9 dsStrong = new Chapter9();
DataSet dsUntyped;
dsUntyped = (DataSet) dsStrong;

, DataSet
DataSet , DataSet

. :
Visual Basic .NET
Dim dsStrongl, dsStrong2 As Chapter9
Dim dsUntyped As DataSet
'
dsStrongl
dsUntyped
dsStrong2


= New ChapterSQ
= CType(dsStrong1, DataSet)
= CType(dsUntyped, Chapter9)

'
dsUntyped = New DataSetO
dsStrong2 = CType(dsUntyped, Chapter9)

Visual C# .NET
Chapter9 dsStrongl, dsStrong2;
DataSet dsUntyped;
//
dsStrongl = new Chapter9();
dsUntyped = (DataSet) dsStrongl;

342

III

: DataSet ADO.NET

dsStrong2 = (Chapter9) dsUntyped;


//
dsUntyped = new OataSetO;
dsStrong2 = (Chapter9) dsUntyped;

, DataSet , DataSet ? DataSet


DataSet, DataSet . Merge DataSet
DataSet:
Visual Basic .NET
Dim dsStrong As New Chapter9()
Dim dsUntyped As New DataSetC)
dsStrong.Merge(dsUntyped)
Visual C# .NET
Chapter9 dsStrong = new Chapter9();
DataSet dsUntyped = new DataSetQ;
dsSt rong.Me rge(dsUntyped);

Merge DataSet .
WriteXml ReadXml,
XML-

, DataSet , . GetChanges DataSet
DataSet,
. DataSet . DataSet, GetCbanges,
DataSet ? , :
Visual Basic .NET
Dim dsStrongAURows As New Chapter9()
' DataSet
'
Dim dsUntyped As DataSet
dsUntyped = dsStrongAllRows.GetChangesO
Dim dsStrongModifiedRows As Cnapter9
dsStrongHodifiedRows = CType(dsUntyped, Chapter9)

DataSet

343

Visual C# .NET
Chapter9 dsStrongAllRows = new Chapter9();
// DataSet
//
DataSet dsUntyped;
dsUntyped = dsStrongAllRows.GetChangesO;
Chapter9 dsStrongModifiedflows;
dsStrongHodifiedRows = (Chapter9) dsUntyped;

DataSet ,
. , Select DataRow. DataSet
,
DataRow.
DataView.
, ,
, DataRow. Row
DataRowView, :
Visual Basic .NET
Dim dsStrong As New Chapter9()
' DataSet
'
Dim vueCustomers As New DataViewfdsStrong.Customers)
Dim rowCustomer As Chapters.CustomersRow
rowCustomer = CType(vueCustomers(Q).Row, Chapters.CustomersRow)

Visual C# .NET
Chapter9 dsStrong = new Chapter9();
// DataSet
//
DataView vueCustomers = new DataView(dsStrong.Customers);
Chapter9.CustomersRow rowCustomer;
rowCustomer = (Chapters.CustonersRow) vueCustomers(0).Row;


? DataSet

. .
DataSet ,
.
. , DataSet.
, , , DataSet
,

344

III

: DataSet ADO.NET

,
. DataSet . . - , ?
. . DataSet . DataSet
Merge DataSet ,
.
. DataSet . DataSet , ,
, .
?
. .
, DataSet -
. .xsd-
DataSet . .xsd, Visual Studio .NET DataSet
,
: , DataSet
, .
.
XML Schema Definition Tool?
. Using Annotations with a Typed DataSet*
.NET Framework SDK
, .
DataSet , NULL. XML Schema Definition Tool .xsd-
, .
.xsd- DataSet
XML Schema . XML . , DataSet DataSet
.xsd- WriteXmlScbema .
ExtendedProperties DataTable DataColumns DataSet:

DataSet

Visual Basic .NET


Dim ds As New DataSetQ
ds.DataSetName = "NameForYourNewClass"
Dim tbl As DataTable = ds. Tables. AddC'TableT)
Dim col As DataColumn
' Dataflow DataTable
tbl.ExtendedProperties.AddC'typedName", "MyTablelRow")
' DataTable DataSet
tbl.ExtendedProperties.Add("typedPlural", "HyTablelRows")
col = tbl.Columns.AddC'StringColuflin", GetType(String))
' NULL, "<Null>"
col.ExtendedProperties.AddC'nullValue", "<Null>")
col = tbl.Columns.Add("StringColumn2", GetType(String))
' NULL, String.Empty
col.ExtendedProperties.AddC'nullValue", String.Empty)
col = tbl.Columns,AddC'IntegerColumn", GetType(Integer))
' NULL,
col.ExtendedProperties.AddC'nullValue", "")
ds. WriteXmlScheina< ": \\\. XSD")

Visual C# .NET
DataSet ds = new DataSetQ;
ds.DataSetName = "NameForYourNewClass";
DataTable tbl = ds.Tables.AddCTableT);
DataColumn col;
// Dataflow DataTable
tbl.ExtendedProperties.AddC'typedName", "MyTablelRow");
// DataTable DataSet
tbl.Extended?roperties.AddC'typedPlural", "HyTablelRows");
col = tbl.Columns.AddC'StringColumn", typeof(string));
// NULL, "<Null>"
col.ExtendedProperties.AddC'nullValue", "<Null>");
col = tbl,Columns.Add("StringColumn2", typeof(string));
// NULL, String.Empty
col.ExtendedProperties,AddC'nullValue", String.Empty);
col = tbl.Columns.AddC'IntegerColumn", typeof(int));
// NULL,
col.ExtendedProperties.AddC'nullValue", "");
ds.WriteXmlSchema<":\\\\\\.XSD");

345

1


, .
.
.
(Sterne Wonder)
-2\ , , , . ADO.NET . , ,
.NET, , , .
ADO.NET
CommandBuilder.
, , .
, ,
, : *?
.
,
: ' . , .
, ADO.NET.
/ . , -

10

347

DataAdapter DataSet , , .
, DataSet ,
DataAdapter. ,
DataSet.
DataSet DataAdapter.
Northwind. . 10-1 ,
SQL Server Query Analyzer . ,
. , - , .
? SQL Analyzer .{Query

(lof.il|itei!iBK.Morttiwjni),M

Unlilleitl'J

" -. 6 Vfu. g
rib

D '.iiancicy

D.DOltPl

)uery batch complied

. 10-1. Northwind
5 , DataSet. , , DataSet. 6,
, DataSet
. , , DataSet
.
5 , DataAdapter Update,
. ,
, :
Visual Basic .NET
' DataTable
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " & _
"FROM [Order Details] WHERE OrderlD = 10503 " & _
"ORDER BY ProductID"
Dim da As New QleDbDataAdapter(strSQL, strConn)
Dim tbl As New DataTable("Order Details")

348

III

: DataSet ADO.NET

da.Fill(tbl)

'
tbl.Rows(0).Delete()
tbl.Rows(1)("Ouantity") = CShort(tbl.Rows(1)("Quantity")) * 2
tbl.Rows.Add(New ObjectO {10503, 1, 24, 16}}
'
Try
da.Update(tbl)
Console.WriteLine("Successfully submitted new changes")
Catch ex As Exception
Console.WriteLine("Call to DataAdapter.Update " & _
"threw exception:" & vbCrLf & ex.Message)
End Try

Visual C# .NET
// OataTable
string strConn, strSOL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " +
"FROM [Order Details] WHERE OrderlD = 10503 " +
"ORDER BY ProductID";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
DataTable tbl = new DataTableC'Order Details");
da.Fill(tbl);
//
tbl.Rows[0],Delete();
tbl.Rows[1]["Quantity"] = (short) (tbl.Rows[1]["Quantity"]) - 2;
tbl.Rows.Addfnew object[] {10503, 1, 24, 18});
//
try
I
da.Update{tbl);
Console.WriteLineC'Successfully submitted new changes");
I
catch (Exception ex)

Console.WriteLine("Call to DataAdapter.Update threw exception:\n"


+ ex.Message);

>
,
. ADO.NET , : Update requires a valid DeleteCommand when passed DataRow
collection with deleted rows* ( Update, DataRow , DeleteCommand).

10

349

- Microsoft .NET Framework . ,


ADO, , . ADO.NET DataAdapter, .
DataAdapter ADO.NET ? : , ADO.NET ,
Data Adapter Configuration Wizard Visual Studio .NET.
,
.


ADO.NET, ,
, ADO.NET, ADO. ADO.NET, ADO .
, ADO * ,
, ADO.NET . , ADO , , ADO.NET.
ADO , DataSet ADO.NET. Recordset ADO . , Recordset
ADO .
, :

Visual Basic ADO 2.x


Dim strConn As String, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " & _
"FROM [Order Details] WHERE OrderlD = 503 " & _
"ORDER BY ProductID"
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Cursor-Location = adUseClient
rs.Open strSQL, strConn, adOpenStatic, adLockBatchOptimistic,
adCmdText
rs.Delete
rs.MoveNext

*
rs.Fields("Quantity") = 2 - rs.Fields("Quantity")
rs.Update

350

111

: DataSet ADO.NET

rs.AddNew
rs.Fields{"OrderID") = 10503
rs.Fields("ProductID") = 1
rs.FieldsC"Quantity") = 24
rs.FieldsC'UnitPrice") = 18
rs.Update

rs.UpdateBatch
rs.Close
en.Close

Recordset ADO, .


Recordset ADO
.
Recordset,
. .
, ADO . . ADO
.
, SQL:
, ADO, , , , SQL- UPDATE.
, , SQL, ADO. ( ),
ADO , ,


Recordset ADO
, , ADO,
. ADO 1.5 ADO,
. .
, , ADO .
Recordset,.UpdateBatcb ADO
Recordset
SQL-, . , SQL- UPDATE, INSERT

10

351

DELETE . ADO .
SQL- SQL Profiler.
, ADO ,
SQL Server sp_execute$ql . :
DELETE FROM [Order Details] WHERE OrderlD = 10503 AND ProductID = 14
UPDATE [Order Details] SET Quantity = 40
WHERE OrderlD = 10503 AND ProductID = 65 AND Quantity = 20
INSERT INTO [Order Details] (OrderlD, ProductID, Quantity, UnitPrice)
VALUES (10503, 1, 24, 18)

,
Recordset, , . . , . Recordset SQL-
, .
, ADO? , ADO
. UPDATE,
, , .

Properties Field ADO:
With rs.Fieldsf'Quantity")
Debug.Print "BaseTableName = " & .Properties("BaseTableName")
Debug,Print "BaseColumnName = " & ,PropertiesC'BaseColumnName")
Debug.Print "KeyColumn = " & .Properties("KeyColumn")
End With

,
ADO, . , ,
, . , , . , ADO Recordset.
ADO * . ,
ADO. ADO , .
Recordset . , ADO, .

352

111 : DataSet ADO.NET


Command ADO,NET
, ADO
. 4, ADO.NET.
, Command DataSet ADO.NET.
Command ADO.NET , ADO. , Command
, . :
UPDATE [Order Details]
SET OrderlD = ?, ProductID = ?, Quantity = ?, UnitPrice = ?
WHERE OrderlD = ? AND ProductID = ? AND
Quantity = ? AND UnitPrice = ?
INSERT INTO [Order Details] (OrderlD, ProductID, Quantity, UnitPrice)
VALUES (?. ?, ?, ?)
DELETE FROM [Order Details]
WHERE OrderlD = ? AND ProductID = ? AND
Quantity = ? AND UnitPrice = ?

UPDATE INSERT
, WHERE.
, ,
.
Command.
,
OleDbConnection .
Visual Basic .NET
Private Function CreateUpdateCommandO As OleDbCommand
Dim strSQL As String
strSQL = "UPDATE [Order Details] " & _
SET OrderlD = ?, ProductID = ?, " & _
Quantity = ?, UnitPrice = ? " & _
WHERE OrderlD = ? AND ProductID = ? AND
Quantity = ? AND UnitPrice = ?"
Dim cmd As New QleDbCommand(strSQL, en)
Dim pc As OleDbParameterCollection = cmd.Parameters
F)c.Add("OrderID_New", OleDbType.Integer)
pc.Add("ProductID Jiew", OleDbType.Integer)
pc. Add(" Quant ityjlew", OleDbType. SmaUInt)

10
pc.Add("UnitPrice_New", OleDbType.Currency)
pc.Add("OrderID_Orig", OleDbType.Integer)
pc.AddC"ProductID_Orig", QleDbType.Integer)
pc.Add("Quantity_Orig", OleDbType.Smalllnt)
pc.Add("UnitPrice_Orig", OleDbType.Currency)
Return cmd
End Function
Private Function CreatelnsertCommandQ As OleDbCommand
Dim strSQL As String
strSQL = "INSERT INTO [Order Details] " & _
(OrderlD, ProductID, Quantity, UnitPrice)
" VALUES (?, ?, ?, ?)"
Dim cmd As New OleDbCommandfstrSQL, en)
Dim pc As OleDbParameterCollection = end.Parameters
pc.Add("OrderlD", OleDbType.Integer)
pc.Add("ProductID", OleDbType.Integer)
pc.Add("Quantity", OleDbType.Smalllnt)
pc.Add("UnitPrice", OleDbType.Currency)
Return cmd
End Function
Private Function CreateDeleteComrnandQ As OleDbCommand
Dim strSQL As String
strSQL = "DELETE FROM [Order Details] " & _
WHERE OrderlD = ? AND ProductID = ? AND '

Quantity = ? AND UnitPrice = ?"


Dim cmd As New OleDbCornmandCstrSQL, en)
Dim pc As OleDbParameterCollection = cmd.Parameters
pc.Add("OrderlD", OleDbType.Integer)
pc.Add("ProductID", OleDbType.Integer)
pc.Add("Quantity", OleDbType.Smalllnt)
pc.Add("UnitPrice", OleDbType,Currency)
Return cmd
End Function

Visual C# .NET
static OleDbCommand CreateUpdateCommandQ
{
string strSQL;
strSQL = "UPDATE [Order Details] " & _
SET OrderlD = ?, ProductID = ?, " +
Quantity = ?, UnitPrice - ? " +

353

354

III : DataSet ADO.NET


WHERE OrderlD = ? AND ProductID = ? AND " +

Quantity = ? AND UnitPrice = ?";


OleDbCommand cmd = new 01eDbCommand(strSQL, en);
OleDbParameterCollection pc = cmd.Parameters;
pc.Add("OrderID_New", OleDbType.Integer);
pc.Add("ProductID_New", OleDbType,Integer);
pc.Add("Quantity_New", OleDbType.Smalllnt);
pc.Add("UnitPrice_New", OleDbType.Currency);
pc.Add("QrderID_Orig", OleDbType.Integer);
pc.Add("ProductID_Orig", OleDbType.Integer);
pc.Add("Quantity_Orig", OleDbType.Smalllnt);
pc.Add("UnitPrice_Orig", OleDbType.Currency);
return cmd;

static OleDbCommand CreatelnsertCommandO


1
string strSQL;
strSQL = "INSERT INTO [Order Details] " +
(OrderlD, ProductID, Quantity, UnitPrtce) " +
VALUES (?, ?, ?, ?)";
OleDbCommand cmd = new 01eDbCommand(strSQL, en);
OleDbParameterCollection pc = cmd.Parameters;
pc.Addf"OrderlD", OleDbType.Integer);
pc.Add("ProductID", OleDbType.Integer);
pc.AddC"Quantity", OleDbType.Sfnalllnt);
pc.Add("UnitPrice", OleDbType,Currency);
return emu;

'
static OleDbCommand CreateDeleteCommandO
<
string strSQL;
StrSQL = "DELETE FROM [Order Details] " +
WHERE OrderlD = ? AND ProductID = ? AND " +
Quantity = ? AND UnitPrice = ?";
OleDbCommand cmd = new 01eDbCommand(strSQL, en);
OleDbParameterCollection pc = cmd.Parameters;
pc,Add("OrderlD", OleDbType.Integer);
pc.Add("ProductID", OleDbType.Integer);
pc.Add("Quantity", OleDbType.Smalllnt);
pc.Add("UnitPrice", OleDbType.Currency);
return cmd;

10

355

Command . DataTable
, (, ). .
ExecuteNonQuery , Command, , . DataRoivAcceptChanges. RowErrar
DataRoiv. .
Visual Basic .NET
Private Sub SubmitChangesByHandO
Dim cmdUpdate As OleDbCommand = CreateUpdateCommandO
Dim cmdlnsert As OleDbConmand = CreatelnsertCommandO
Dim cmdDelete As OleDbCommand = CreateDeleteCommandO
Dim row As Dataflow
Dim IntRowsAffected As Integer
Dim dvrs As DataViewRowState
dvrs = DataViewHowState.ModifiedCurrent
Or DataViewRowState.Deleted Or DataViewRowState.Added
For Each row In tbl.Select{"", "", dvrs)
Select Case row.RowState
Case DataRowState.Modified
intRowsAffected = SubmitUpdate(row, cmdUpdate)
Case DataRowState.Added
intRowsAffected = Submitlnsert(row, cmdlnsert)
Case DataRowState.Deleted
intRowsAffected = SubmitDelete{row, cmdDelete)
End Select
If intRowsAffected = 1 Then
row.AcceptChangesO
Else
row.RowError = "Update attempt failed"
End If
Next row
End Sub
Private Function SubmitUpdate(ByVal row As Dataflow, _
ByVal cmd As OleDbCommand) As Integer
Dim pc As OleDbParameterCollection = cmd.Parameters
pc("OrderID_New").Value = row("OrderID")
pc("ProductID_New").Value = row("ProductID")
pc("Quantity_New").Value = row("Quantity")
pc("UnitPrlce_New").Value = rowC'UnitPrice")
pc("OrderID_Orig").Value = row("OrderID", _
DataRowVersion.Original)
pc("Quantity_Qrig"}.Value = row("Quantity", _
DataRowVersion.Original)

356

III : DataSet ADO.NET

pc("ProductID_Orig").Value = row("ProductID", _
DataRowVersion.Original)
pc("UnitPrice_Orig").Value = row("UnitPrice",
DataRowVersion.Original)
Return cmd.ExecuteNonQuery
End Function
Private Function SubmitInsert(8yVal row As DataRow, _
ByVal cmd As OleDbCommand) As Integer
Dim pc As OleDbParameterCollection = cmd.Parameters
pcf'OrderlD").Value = row("OrderID")
pcC'ProductID").Value = row("ProductID")
pc("Quantity").Value = row("Quantity")
pcC'UnitPrice").Value = row("UnitPrice")
Return cmd.ExecuteNonQuery
End Function
Private Function SubmitDelete(ByVal row As OataRow,
ByVal cmd As OleDbCommand) As Integer
Dim pc As OleDbParameterCollection = cmd.Parameters
pc{"OrderID").Value = row("OrderID", DataRowVersion.Original)
pcC'ProductID").Value = row("Product10", DataRowVersion.Original)
pc("Quantity").Value = row("Quantity", DataRowVersion.Original)
pc("UnitPrice").Value = row("UnitPrice", DataRowVersion.Original)
Return cmd.ExecuteNonQuery
End Function

Visual C# .NET
static void SubmitChangesByHand()
<
OleDbCommand cmdUpdate = CreateUpdateCommandO;
OleDbCommand cmdlnsert = CreatelnsertComrnandO;
OleDbCommand cmdDelete = CreateDeLeteCommandQ;
DataViewRowState dvrs;
dvrs = DataViewRowState.ModifiedCurrent |
DataViewRowState.Deleted | DataViewRowState.Added;
int intflowsAffected = 0;
foreach {Dataflow row in tbl.Select("", "", dvrs))
{
switch (row.RowState)
!
case DataRowState.Modified:
intRowsAffected = SubmitUpdate{row, cmdUpdate);
break;
case DataRowState.Added:
intRowsAffected = Submitlnsert{row, cmdlnsert);
break;
case DataRowState.Deleted:
intRowsAffected = SubmitDelete(row, cmdDelete);

10

break;
}
if (irrtRowsAffected == 1)
row. AcceptChangesQ ;
else
row. RowError = "Update attempt failed";

static int SubmitUpdate(DataRow row, 01 subcommand cmd)


{
OleDbParameterCollection pc = cmd. Parameters;
pc["OrderID_New"]. Value = row["OrderID"];
pc["ProductID_New"]. Value = row["ProductID"];
pc["Quantity_New"]. Value = row["Quantity"];
pc["UnitPrice_New"]. Value = row["UnitPrice"];
pct"OrderID_Orig"]. Value = row["OrderID",
DataRowVersion. Original];
pc["ProductID_Orig"]. Value = row["ProductID",
DataRowVersion. Original];
pc["Quantity_Orig"]. Value = row["0uantity",
DataRowVersion. Original];
pc["UnitPrice_Orig"]. Value = row["UnitPrice",
DataRowVersion. Original];
return cfnd.ExecuteNonQueryO;
static int SubmitInsert(DataRow row, OleDbCommand cmd)
{
OleDbParameterCollection pc = cmd. Parameters;
pc["OrderIO"]. Value = row["Order!D"];
pc["Product!D"]. Value = row["ProductID"];
pc[Quantity"]. Value = row["Quantity"];
pc["UnitPrice"]. Value = row["UnitPrice"];
return cmd. ExecuteNonQueryO;
static int SubmitDeletefDataRow row, OleDbCommand cmd)
{

OleDbParameterCollection pc = cmd. Parameters;


pc["Order!D"]. Value = row["OrderID", DataRowVersion. Original];
pc["ProductID"]. Value = row["ProductID",
DataRowVe rsion . 0 riginal ] ;
pc["Quantity"]. Value = row[ "Quantity", DataRowVe rsion. Original];
pc["UnitPrice"]. Value = row["UnitPrice",
DataRowVersion, Original];
return cmd. ExecuteNonQueryO;

357

358

: DataSet ADO.NET


DataTable.Select.
For For Each
Roivs DataTable.
AcceptChanges
DataRow. .
Select DataRow, , ,
, . Rows
DataTable, - .
.
DataTable, . ,
, . , ,
DataTable . ResetOrder, .
Visual Basic .NET
Dim en As OleDbConnection
Dim da As OleDbDataAdapter
Dim tbl As DataTable = GenTableO
Sub Main()
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" 4 _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " &
"FROM [Order Details] WHERE OrderlD = 10503 " & _
"ORDER BY ProductID"
en = New OleDbConnection(strConn)
da = New OleDbDataAdapterCstrSQL, en)
cn.0pen()
ResetOrderO
da.Fill(tbl)
DisplayOrder("Initial contents of database")
ModifyOrderO
DisplayOrder("Modified data in DataSet")
SubmitChangesByHand()
tbl.ClearO
da.Fill(tbl)
DisplayOrder("New contents of database")
cn.Close()
End Sub

10
Private Sub ModifyOrderO
Dim row As OataRow
row = tbl.Rows(O)
row.DeleteO
row = tbl.Rows{1)
row("Quantity") = CType{row("Quantity"), Int16) - 2
row = tbl.Newflow
row("OrderID") = 10503
row("ProductIO") = 1
row("Quantity") = 24
row("UnitPrice") = 18.0
tbl.Rows.Add(row)
End Sub
Public Sub DisplayOrderfByVal strStatus As String)
Dim row As DataRow
Dim col As DataColumn
Console.WriteLine(strStatus)
Console,WriteLine("
OrderlD
ProductID
"Quantity
UnitPrice")
For Each row In tbl.SelectC"", "ProductID")
For Each col In tbl.Columns
Console.Write(vbTab & row(col) & vbTab)
Next
Console.WriteLineC)
Next
Console.WriteLinef)
End Sub

" &

Private Sub ResetOrderQ


Dim strSQL As String
Dim cmd As OleDbComrcand = cn.CreateCommand()
StrSQL = "DELETE FROM [Order Details] WHERE OrderlD = 10503"
cmd.CommandText = strSQL
cmd. ExecuteNonQueryO
StrSQL = "INSERT INTO [Order Details] " & _
(OrderlD, ProductID, Quantity, UnitPrice) " & _
VALUES (10503, 14, 70, 23.25) "
cmd.CommandText = strSQL
cmd. ExecuteNonQueryO
strSQL = "INSERT INTO [Order Details] " & _
(OrderlD, ProductID, Quantity, UnitPrice) " & _
VALUES (10503, 65, 20, 21.05)"
cmd.CommandText = strSQL
cmd. ExecuteNonQueryO
End Sub

359

360

111

: DataSei ADO.NET

Public Function GenTableQ As DataTable


Dim tbl As New DataTable("Order Details")
Dim col As DataColumn
With tbl.Columns
col = .Addf'OrderlD", GetType(Integer))
col.AllowDBNull = False
col = .AddC'ProductID", GetType(Integer))
col.AllowDBNull = False
col = .AddC'Quantity", GetType(Int16})
col.AllowDBNull = False
col = .AddC'UnitPrice", GetType{Decimal}>
col.AllowDBNull = False
End With
tbl. PrimaryKey = New DataColumnO {tbl-Columns("OrderID"),
tbl.ColumnsC'ProductlD")}
Return tbl
End Function

Visual C# .NET
static OleDbConnection en;
static OleDbDataAdapter da;
static DataTable tbl;
static void Main(string[] args)
{
string strConn, strSQL;
strConn = "Provider=SQLOlEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " +
"FROM [Order Details] WHERE OrderlD = 10503 " +

"ORDER 8Y ProductID";
en = new OleDbConnection(strConn);
da = new 01eDbOataAdapter(strSQL, en);
tbl = GenTablef);
cn.OpenQ;
ResetOrderQ;
da.Fill(tbl);
DisplayOrder("Initial contents of database");
ModifyOrderO;
DisplayOrder("Modified contents of DataSet");
SubmitChangesByHand();
tbl.ClearO;
da.Fill(tbl);
DisplayOrderC'New contents of database");
cn.Close();

static void ModifyOrderO

10

DataRow row;
row = tbl.Rows[0];
row.DeleteC);
row = tbl.Rows[1];
row["Quantity"] = (Int16) row["Quantity"]
row = tbl.NewRowQ;
row["OrderID"] = 10503;
row["ProductID"] = 1;
rowf'Quantity"] = 24;
row["UnitPrice"] = 18.0;
tbl, Rows. Add(row);
static void DisplayQrder(string strStatus)
{
Console, WriteLine( strStatus);
Console. WriteLinef"
OrderlD
ProductID
.
"Quantity
UnitPrice");
fo reach (DataRow row in tbl.Select("", "ProductID"))
{
foreacri(DataColurnn col in tbl. Columns)
Console, Write("\t" + row[col] + "\t");
Console. WriteLineO;
}
Console. WriteLineO;

" +

static void ResetOrderC)


<
string strSQL;
OleDbCommand cmd = cn.CreateCommandO;
strSQL = "DELETE FROM [Order Details] WHERE OrderlO = 10503'
cmd.CommandText = strSOL;
cmd . ExecuteNonQue ry( ) ;
strSOL = "INSERT INTO [Order Details] " +
(OrderlD, ProductID, Quantity, UnitPrice) " +
VALUES (10503, 14, 70, 23.25) "
cnd.CommandText = strSQL;
cmd. ExecuteNonQue ry();
StrSQL = "INSERT INTO [Order Details] " +
(OrderlD, ProductID, Quantity, UnitPrice) " +
VALUES (10503, 65, 20, 21.05)";
cmd.CommandText = strSQL;
cmd. ExecuteNonQue ry();
static DataTable GenTableQ

1 3-5958

361

362

111 : DataSet ADO.NET

DataTable tbl = new DataTable("Order Details");


DataColumn col;
col = tbl.Columns.Add("Order-ID", typeof(int));

col.AllowDBNull = false;
col = tbl.Columns.Add("ProductID", typeof(int));
col.AllowDBNull = false;
col = tbl.Columns.Add("Quantity", typeof(Int16));
col.AllowDBNull = false;
col = tbl.Columns.Add("UnitPrice", typeof(Decimal));
col.AllowDBNull = false;
tbl.PrimaryKey = new DataColumn[] {tbl.Columns["OrderID"],
tbl.ColumnspProductlD"]};
return tbl;
!

. ,
Command, . SubmitCbangesByHand . DataTable, , DataRow, , , ,
,
DataRow.
, ,
DataAdapter. .


DataAdapter ADO.NET
5 DataAdapter DataTable. DataAdapter.
DataSet,
, DataAdapter
, :
DataAdapter,
CommandBuilder.
Data Adapter Configuration
Wizard.
,
.

DataAdapter
DataAdapter , Command.
, SelectCommand Command, DataAdapter DataTable. -

10

363

, UpdateCommand, InsertCommand DeleteCommand, Command, DataAdapter .


ADO.
* . , DataAdapter ,
Command.
Update DataAdapter DataSet,
DataSet , Data-Table DataRou*. , DataAdaplerUpdate, DataAdapter Command.
, SubmitCbangesByHand, DataAdapter.Update.


SubmtiCbangesByHana' . ,
.
: SubmitUpdate, Submitlnsert SubmilDelele.

.
DataAdapter .
UPDATE [Order Details]
SET OrderlD = ?, ProductID = ?, Quantity = ?, UnitPrice = ?'
WHERE OrderlD = ? AND ProductID = ? AND
Quantity = ? AND UnitPrice = ?
INSERT INTO [Order Details] (OrderlD, ProductID, Quantity, UnitPrice)
VALUES (?, ?, ?, ?)
DELETE FROM [Order Details]
WHERE OrderlD = ? AND ProductID = ? AND
Quantity = ? AND UnitPrice = ?

Command,
DataAdapter, Parameter
ADO.NET. DataAdapter:
SourceColumn SourceVersion.
, Parameter DataColumn
Data-Table. DataAdapter
, Value Parameter, , SubmitUpdate, Submitlnsert
SubmitDelete. . 10-2.

Command, SourceColumn it SourceVersion
Parameter. SourceVersion DataRouVersion.Current,
, Parameter .

364

III : DataSet ADO.NET


OrderlD

ProductiD

Quantity

LJnitPrice

10503

65

20

21.05

DstaRow
( )

UPDATE [Order Details]


\
\
^
SET OrcterlD = ?, ProductiD = ?, Quantity = ?, UnitPrice = ?
WHERE OrderlD = ? AND ProductiD = ? AND Quantity = ? AND UnitPrice = ?
DataRow
( )

10503

65

40

21.05

QrderiD

ProductlD

Quantity

UnitPrice

. 10-2. Parameter DataColumn


Visual Basic .NET
Private Function CreateDataAdapterUpdateCommandO As OleDbCommand
Dim strSQL As String
strSQL = "UPDATE [Order Details] " & _
SET OrderlD = ?, ProductiD = ?, " & _
Quantity = ?, UnitPrice = ? " & _
WHERE OrderlD = ? AND ProductiD = ? AND " & _
Quantity = ? AND UnitPrice = ?"
Dim cmd As New QleDbCommandCstrSQL, en)
Dim pc As OleDbParameterCollection = cmd.Parameters
pc.Add("OrderID_New", OleDbType.Integer, 0, "OrderlD")
pc.Add("ProductIDJIew", OleDbType.Integer, 0, "ProductiD"}
pc.Add("Quantity_New", OleDbType.Smalllnt, 0, "Quantity")
pc.Add("UnitPrice_New", OleDbType.Currency, 0, "UnitPrice")
Dim param As OleDbParameter
param = pc.Add("OrderID_Orig", OleDbType.Integer, 0, "OrderlD")
param.SourceVersion = DataRowVersion.Original
param = pc.Add("ProductIDJ3rig", OleDbType.Integer, 0,
"ProductiD").
param.SourceVersion = DataRowVersion.Original
param = pc.Add("Quantity_Orig", OleDbType.Smalllnt, 0,
"Quantity")
param.SourceVersion = DataRowVersion.Original
param = pc.Add("UnitPrice_Orig", OleDbType.Currency, 0,
"UnitPrice")
param.SourceVersion = DataRowVersion.Original
Return cmd
End Function
Private Function CreateDataAdapterlnsertCommandO As OleDbCommand

10
Dim strSQL As String
strSQL = "INSERT INTO [Order Details] " & _
(OrderlD, ProductID, Quantity, UnitPrice) " &
11
VALUES (?, ?, ?, ?)"
Dim cmd As New OleDbCommandCstrSQL, on)
Dim pc As OleDbParameterCollection = cmd.Parameters
pc.Add("OrderlD", OleDbType.Integer, 0, "OrderlD")
pc.Add("ProductID", OleDbType.Integer, 0, "ProductID")
pc.Add("Quantity", OleDbType.Smalllnt, 0, "Quantity")
pc.Add("UnitPrice", OleDbType.Currency, 0, "UnitPrice")
Return cmd
End Function
Private Function CreateDataAdapterDeleteCommand() As OleDbCommand
Dim strSQL As String
StrSQL = "DELETE FROM [Order Details] " & _
WHERE OrderlD = ? AND ProductID = ? AND " & _

Quantity = ? AND UnitPrice = ?"


Dim cmd As New 01eDbCommand(strSQL, en)
Dim pc As OleDbParameterCollection = cmd.Parameters
Dim param As QleDbParatneter
pc.Add("OrderID", OleDbType.Integer, 0, "OrderlD")
param.SourceVersion = DataRowVersion.Original
pc.AddC'ProductID", OleDbType.Integer, 0, "ProductID")
param.SourceVersion = DataRowVersion.Original
pc.Add("Quantity", OleDbType.Smalllnt, 0, "Quantity")
param.SourceVersion = DataRowVersion.Original
pc.Add("UnitPrice", OleDbType.Currency, 0, "UnitPrice")
pa ram.SourceVersion = DataRowVersion.Original
Return cmd
End Function

Visual C# .NET
static OleDbCommand CreateDataAdapterUpdateCommandO
{
string strSQL;
StrSQL = "UPDATE [Order Details] " & _
SET OrderlD = ?, ProductID = ?, " +
Quantity = ?, UnitPrice = ? " +
WHERE OrderlD = ? AMD ProductIO = ? AND " +
Quantity = ? AND UnitPrice = ?";
OleDbCommand cmd = new 01eDbCommand(strSQL, en);
OleDbParameterCollection pc = cmd.Parameters;
pc.Add("OrderID_New", OleDbType.Integer, 0, "OrderlD");

365

366

111 : DataSet ADO. NET


pc.Add("ProductID_New", OleDbType. Integer, 0, "ProductID");
pc.Add("Quantity_New", OleDbType. Smalllnt, 0, "Quantity");
pc. Add("UnltPrice_New", OleDbType. Currency, 0, "Unit Price");
OleDbParameter param;
param = pc.Add("Order!D_Orig", OleDbType. Integer, 0, "OrderlD");
param. SourceVersion = DataRowversion. Original;
param = pc.Add("ProductID_Orig", OleDbType. Integer, 0,
"ProductID");
param. SourceVersion = DataRowversion. Original;
param = pc.Add("Ouantity_Orig", OleDbType. Smalllnt, 0,
"Quantity");
param. SourceVersion = DataRowversion. Original;
param = pc.Add("UnitPrice_Orig", OleDbType. Currency, 0,
'UnitPrice");
param. SourceVersion = DataRowversion. Original;
return cmd;

static OleDbCommand CreateDataAdapterInsertCommand( )


i
string strSQL;
strSQL = "INSERT INTO [Order Details] " +

(OrderlD, ProductID, Quantity, UnitPrice) " +


VALUES {?, ?, ?, ?)";
OleDbCommand cmd = new OleDbComniancKstrSQL, en);
OleDbParameterCollection pc = cmd. Parameters;
pc,Add("OrderID", OleDbType. Integer, 0, "OrderlD");
pc.Add("ProductID", OleDbType. Integer, 0, "ProductID");
pc.Add( "Quantity". OleDbType. Smalllnt, 0, "Quantity");
pc.Add( "Unit Price", OleDbType. Currency, 0, "UnitPrice");
return cmd;
i

static OleDbCommand CreateOataAdapterDeleteCommandO


{
string strSQL;
strSQL = "DELETE FROM [Order Details] " +
WHERE OrderlD = ? AND ProductID = ? AND " +

Quantity = ? AND UnitPrice = ?";


OleDbCommand cmd = new 01eDbCommand(strSQL, en);
OleDbParameter param;
OleDbParameterCollection pc = cmd. Parameters;
param = pc.Add( "OrderlD", OleDbType. Integer, 0, "OrderlD");
param. SourceVersion = DataRowversion. Original;
param = pc.AddC'ProductID", OleDbType. Integer, 0, "ProductID");

10

367

param.SourceVersion = DataRowVersion. Original;


param = pc.Add("Quantity", QleDbType.Smalllnt, 0, "Quantity");
param.SourceVersion = DataRowVersion. Original;
param = pc.AddC'UnitPrtce", OleDbType. Currency, 0, "UnitPrice");
param.SourceVersion = DataRowVersion. Original;
return cmd;
}

SubmttChangesByHand, SubmitUpdate, Siibmittnsert SubmitDt-lete


;
Visual Basic .NET
Private Sub SubmitChangesViaDataAdapter()
da.UpdateCommand = CreateDataAdapterUpdateCommandQ
da. InsertCommand = CreateDataAdapterlnsertCommandO
da.DeleteCommand = CreateDataAdapterDeleteCommandO
da.Update(tbl)
End Sub
Visual C# .NET
static void SubmitChangesViaDataAdapterO
{
da.UpdateCommand = CreateDataAdapterUpdateCommandO;
da. InsertCommand = CreateDataAdapterlnsertCommandO;
da.DeleteCommand = CreateDataAdapterDeleteCommandO;
da.Update(tbl);



, ADO, Recordset.UpdateBatch
.
, DataAdapter . ,
Command, DataAdapter . .
-, Northwind , , Order Details. , ,
SQL Server Query Analyzer.
MSDE , , SQL Server Query Analyzer,
CreateSprocs ( )
.

368

111

: DataSet ADO.NET

USE Northwind

GO
CREATE PROCEDURE spUpdateDetail

(@OrderID_New int, @ProductID_New int,


@Quantity_New smallint, @UnitPrice_New money,
@OrderID_Orig int, @ProductID_Orig int,
@Quantity_Orig smallint, @UnitPrice_Qrig money)

AS
UPDATE [Order Details]
SET OrderlD = @OrderlD_New, ProductID = @ProductID_New,
Quantity = @Quantity_New, UnitPrice = @UnitPrice_New
WHERE OrderlD = @OrderID_Orlg AND ProductID = @ProductID_Orig AND
Quantity = @Quantity_Orig AND UnitPrice = 3UnitPrice_Orig
GO

CREATE PROCEDURE spInsertDetail


(@OrderID int, gProductlD int,
^Quantity smallint, ^UnitPrice money)
AS
INSERT INTO [Order Details]
(OrderlD, ProductID, Quantity, UnitPrice)
VALUES (@OrderID, 0ProductID, ^Quantity, @UnitPrice)

GO
CREATE PROCEDURE spDeleteDetail
(@OrderID int, ^ProductID int,
Quantity smallint, UnitPrice money)
AS
DELETE FROM [Order Details]
WHERE OrderlD = @OrderID AND ProductID = ProductID AND
Quantity = ^Quantity AND UnitPrice = UnitPrice

Order Details,
Command,
DataAdapter.Update.
, Command, . , . ,

Commands DataAdapter. SubmitCbangesViaStoredProcedures.
Visual Basic .NET
Private Sub SubmitChangesViaStoredProceduresO
da.UpdateCommand = CreateUpdateViaSPComraandO
da.InsertCommand = CreatelnsertViaSPCommandO

10
da.DeleteCommand = CreateDeleteViaSPCommandQ
da.Update(tbl)
End Sub
Private Function CreateUpdateViaSPCommandO As OleDbCommand
Dim cmd As New 01eDbCommand("spUpdateDetail", en)
cmd.CommandType = CommandType.StoredProcedure
Dim pc As OleDbParameterCollection = cmd.Parameters
pc.Add("OrderlD_New", OleDbType.Integer, 0, "OrderlD")
pc.Add("ProductID_New", OleDbType,Integer, 0, "ProductID")
pc.Add("Quantity_New", OleDbType.Smalllnt, 0, "Quantity")
pc.Add("UnitPrice_New", OleDbType.Currency, 0, "UnitPrice")
Dim param As OleDbParameter
param = pc.Add("OrderID_Orig", OleDbType.Integer, 0, "OrderlD")
param.SourceVersion = DataRowVersion.Original
param = pc.Add("ProductID_Orig", OleDbType,Integer, 0,
"ProductID")
param.SourceVersion = DataRowVersion.Original
param = pc.Add("Quantity_Orig". OleDbType.Smalllnt, 0,
"Quantity")
pa ram.SourceVersion = DataRowVersion.Original
param = pc.Add("UnitPrtce_Orig", OleDbType.Currency, 0.
"UnitPrice")
param.SourceVersion = DataRowVersion.Original
Return cmd
End Function
Private Function CreatelnsertViaSPCommandO As OleDbCommand
Dim cmd As New OleDbCommandC'spInsertDetail", en)
cmd.CommandType = CommandType.StoredProcedure
Dim pc As OleDbParameterCollection = cmd.Parameters
pc.AddC"OrderlD", OleDbType.Integer, 0, "OrderlD")
pc.Add("ProductID", OleDbType.Integer, 0, "ProductID")
pc.Addt"Quantity", OleDbType.Smalllnt, 0, "Quantity")
pc.Add("UnitPrice", OleDbType.Currency, 0, "UnitPrice")
Return cmd
End Function
Private Function CreateDeleteViaSPCommandO As OleDbCommand
Dim cmd As New 01eDbCommand{"spDeleteDetail", on)
cmd.CommandType = CommandType.StoredProcedure
Dim pc As OleDbParameterCollection = cmd.Parameters
Dim param As OleDbParameter
param = pc.Add("OrderID", OleDbType.Integer, 0, "OrderlD")

369

370

III

: DataSet ADO.NET

param.SourceVersion = DataRowVersion.Original
param = pc.Add("ProductID", OleDbType.Integer, 0, "ProductlD")
param.SourceVersion = DataRowVersion.Original
param = pc.AddC"Quantity", OleDbType,Smalllnt, 0, "Quantity")
param.SourceVersion = DataRowVersion.Original
param = pc.Add("UnitPrice", OleDbType.Currency, 0, "UnitPrice")
param.SourceVersion = DataRowVersion.Original
Return cmd
End Function

Private Sub CreateSprocsO


Dim cmd As OleDbCommand = cn.CreateComrnand
Dim strSQL As String
strSQL = "CREATE PROCEDURE spUpdateDetail " & vbCrLf & _
(@OrderID_New int, @ProductID_New int, " & vbCrLf & _
@Quantity_New smallint, " & vbCrLf &
@UnitPrice_New money, " & vbCrLf &
@OrderID_Orig int, " & vbCrLf & _
@ProductID_Orig int, " & vbCrLf &
@Quantity_Orig smallint, " & vbCrLf &
@UnitPrice_Orig money) " & vbCrLf &
"AS " & vbCrLf & _
"UPDATE [Order Details] " & vbCrLf & _
SET OrderlD = @OrderID_New, " & vbCrLf & _
ProductlD = @ProductID_New, " & vbCrLf & _
Quantity = @Quantity_New, " & vbCrLf & _
UnitPrice = @UnitPrice_New " & vbCrLf &
WHERE OrderlD = @OrderID_Qrig AND " & vbCrLf &_
ProductlD = @ProductID_Orig AND " & vbCrLf &
Quantity = @Quantity_Orig AND " & vbCrLf 4
UnitPrice = @UnitPrice_Orig"
cmd.ConnnandText = strSQL
cmd. ExecuteNonQueryO
strSQL = "CREATE PROCEDURE spInsertDetail " & vbCrLf & _
(@OrderID int, @ProductID int, " & vbCrLf & _
^Quantity smallint, ^UnitPrice money) " & vbCrLf &
"AS " & vbCrLf & _
"INSERT INTO [Order Details] " & vbCrLf & _
(OrderlD, ProductlD, Quantity, UnitPrice} " & vbCrLf & _
VALUES (@OrderID, @ProductID, ^Quantity, @UnitPrice)"
cmd.CommandText := strSQL
end. ExecuteNonQueryO
strSQL = "CREATE PROCEDURE spDeleteDetail " & vbCrLf & _
(OrderlD int, Productld int, " & vbCrLf &
^Quantity smallint, @UnitPrice money) " & vbCrLf &
"AS " & voCrLf &

10

"DELETE FROM [Order Details] " & vbCrLf & _


WHERE OrderlD = @OrderID AND " & vbCrLf & _

ProductID = @ProductID AND " & vbCrLf &


Quantity = ^Quantity AND UnitPrice = @UnitPrice"
cmd.CommandText = strSQL
cmd. ExecuteNonQueryC )
End Sub

Visual C# .NET
static void SubmitChangesViaStoredProcedu res( )
{
da.UpdateCommand = CreateUpdateViaSPCommandO;
da.InsertCommand = CreatelnsertViaSPCommandO;
da.DeleteComrnand = CreateDeleteViaSPCommandO;
da.Update(tbl);
static OleDbCommand CreateUpdateViaSPCommandO
{
OleDbCommand cmd = new OleDbCommandC'spUpdateDetail", en);
cmd. CommandType = CommandType. StoredProcedure;
OleDbParameterColLection pc = cmd. Parameters;
pc.Add("OrderID_New", OleObType. Integer, 0, "OrderlD");
pc.Add( "Product ID_New", OleDbType. Integer, 0, "ProductID");
pc.Add("Guantity_New", OleDbType. Smalllnt, 0, "Quantity");
pc.Add("UnitPrice_New", OleDbType. Currency, 0, "UnitPrice");
OleDbParameter param;
param = pc.Add("OrderID_Orig", OleDbType. Integer, 0, "OrderlD");
param. SourceVersion = DataRowVersion. Original;
param = pc.Add("ProductID_Orig", OleDbType. Integer, 0, "ProductID");
param. SourceVersion = DataRowVersion. Original;
param = pc.Add("Quantity_Orig", OleDbType. Smalllnt, 0, "Quantity");
param. SourceVersion = OataRowVerston. Original;
param = pc.Add( "Unit Price_0 rig", OleDbType. Currency, 0, "UnitPrice");
param. SourceVersion = DataRowVersion. Original;
return cmd;
static OleDbCommand CreatelnsertViaSPCommandO
i

OleDbCommand cmd = new OleDbCommandC'spInsertDetaiL", en);


cmd.CommandType = CommandType. StoredProcedure;
OleDbPararrteterCollection pc = cmd. Parameters;
pc.Add("OrderrD", OleDbType. Integer, 0, "OrderlD");
pc.Add("ProductID", OleDbType. Integer, 0, "ProductID");

371

372

III : DataSet ADO.NET


.Add("Quantity", OleDbType.Smalllnt, 0, "Quantity"};
pc.Add("UnitPrice", OleDbType.Currency, 0, "UnitPrice");
return cmd;

static OleDbCommand CreateDeleteViaSPCommandO


{
OleDbCommand cmd = new OleDbCoromandC'spDeleteDetail", en);
cmd.CommandType = CommandType.StoredProcedure;
OleDbParameterCollection pc = cmd.Parameters;
OLeDbParameter param;
param = pc.Add("Order!D", OleDbType.Integer, 0, "QrderlD");
param.SourceVersion = DataRowVersion,Original;
param = pc.Add("ProductID", OleDbType.Integer, 0, "ProductID");
param.SourceVersion = DataRowVersion.Original;
param = pc,Add{"Quantity", OleDbType.Smalllnt, 0, "Quantity");
param.SourceVersion = DataRowVersion.Original;
param = pc.Add("UnitPrice", OleDbType.Currency, 0, "UnitPrtce");
param.SourceVersion = DataRowVersion.Original;
return cmd;

}
static void CreateSprocsQ

{
OleDbCommand cmd = cn.CreateCommandC);
string strSQL;
strSQL = "CREAJE PROCEDURE spUpdateDetail \n\r" +
(@OrderID_New int, @ProductID_New int, \n\r" +
@Quantity_New smallint, @UnitPrice_New money, \n\r" +
@OrderID_Orig int, @ProductID_Orig int, \n\r" +
@Quantity_Orig smallint, @UnitPrice_Orig money) \n\r" +
"AS \n\r" +
"UPDATE [Order Details] \n\r" +
SET OrderlD = @OrderID_New, \n\r" +
ProductID = @ProductIDjJew, \n\r" +
Quantity = @Quantity_New, \n\r" +
UnitPrice = @UnitPrice_New \n\r" +
WHERE OrderlD = @QrderID_Orig'AND \n\r" +
ProductID = @ProductID_Orig AND \n\r" +
Quantity = @Quantity_Orig AND \n\r" +
UnitPrice = @UnitPrice_Orig";
cmd.CommandText = strSQL;
cmd.ExecuteNonQueryO;
strSQL = "CREATE PROCEDURE spInsertDetail \n\r" +

C^OrderlD int, ProductID int, \n\r" +

10

373

^Quantity smallint, @UnitPrice money) \n\r" +


"AS \n\r" +
"INSERT INTO [Order Details] \n\r" +
(OrderlD, ProductID, Quantity, UnitPrice) \n\r" +
VALUES (@OrderID, &ProductID, ^Quantity, @>UnitPrice)";
cmd.CommandText = strSQL;
cmd.ExecuteNonQuery();
strSQL = "CREATE PROCEDURE spDeleteDetail \n\r" +
(@OrderID int, @ProductID int, \n\r" +
^Quantity smallint, @UnitPrice money) \n\r" +
"AS \n\r" +
"DELETE FROM [Order Details] \n\r" +
WHERE OrderlD = @OrderID AND \n\r" +
ProductID = @ProductID AND \n\r" +
Quantity = Quantity AND UnitPrice = @UnitPrice'
crnd. CommandText = strSOL;
cmd.ExecuteNonQue ry();


. Microsoft, DataAdapter ADO.NET . ; -
.
,
, , . ADO ,
, . ADO.NET DataSet
, , ,
.

. ,
ADO, , , , .
, .

374

III

: DataSet ADO.NET


ADO. -, . ,
DataAdapter ADO.NET
ADO. , .
, 1 . -?, ?, <
WHERE UPDATE DELETE?,
OleDbType , /?
, .
.


CommandBuilder
ADO.NET
,
CommandBuilder, ADO. CommandBuilder
DataAdapter^ CommandBuilder
, SelectCommand DataAdapter.
CommandBuilder,
, Order Details. OleDhCommandBuilder, OleDbDataAdapter. , InsertCommand
CommandBuilder .
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, ProductlD, Quantity, UnitPrice " & _

"FROM [Order Details] WHERE OrderlD = 10503 " i _


"ORDER BY ProductlD"
Dim da As New 01eDbDataAdapter(strSQL, strConn}
Dim cb As New OleDbCommandBuilder(da)
Console.WriteLine(cb,GetInsertCommand.CommandText)

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";

10

375

strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " +


"FROM [Order Details] WHERE OrderlD = 10503 " +
"ORDER BY ProductID";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
OleDbCommandBuilder cb = new OleDbCommandBuiLder(da);
Console.WriteLine(cb.GetInsertCommand().CommandText);

, , :
INSERT INTO Order Details( OrderlD , ProductID , Quantity , UnitPrice )
VALUES ( ? , ? , ? , ? )

CommandBuilder
, CommandBuilder UPDATE, INSERT
DELETE, . ADO.
CommandBuilder , . CommandBuilder ,
:
;
;
.
, , CommandBuilder : . CommandBuilder , ?
.
CommandBuilder ,
, SelectCommand DataAdapter,
4- ExecuteReader Command ,
:
Visual Basic .NET
Dim strConn, strSQL As String
StrConn = "Provider=SQLOLEDB; Data Source=(local)\NetSDK; " &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " & _
"FROM [Order Details] WHERE OrderlD = 10503 " & _
"ORDER BY ProductID"
Dim en As New OleDbConnection(strConn)
Dim cmd As New 01eDbCommand(strSQL, en)
cn.0pen{)
Dim rdr As OleDbDataReader
rdr = cmd.ExecuteReader(CommandBehavior.SchemaOnly Or _
ComtnandBehavior.Keylnfo)
Dim tbl As DataTable = rdr.GetSchemaTable
rdr.Closef)

376

III : DataSet ADO.NET

cn.CloseO
Dim row As DataRow
Dim col As DataColumn
For Each row In tbl.Rows
For Each col In tbl.Columns
Console.WriteLineCcol.ColumnNarne & ": " & row(col).ToString)
Next col
Console. Writel_ine()
Next row

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT OrderlD, ProductlD, Quantity, UnitPrice " +
"FROM [Order Details] WHERE OrderlD = 10503 " +
"ORDER BY ProductlD";
OleDbConnection en = new OleDbConnection(strConn);
OleDbCommand cmd = new 01eDbCominand{strSQL, en);
cn.OpenO;
OleDbDataReader rdr;
rdr = cmd.ExecuteReader(CommandBehavior,SchemaOnly |
CommandBehavior.Keylnfo);
DataTable tbl = rdr.GetSchemaTableO;
rdr.Close();
cn.CloseO;
foreach (DataRow row in tbl.Rows)
{
foreach {DataColumn col in tbl.Columns)
Console.WriteLine(col.ColumnName + ": " +
row[col].ToStringQ);
Console. WriteLineO;
'
, , CommandButtder , .
? ?
?
? .., ..


CommandBuilder
, CommandBuilder, ,
,
CommandBuilder. -,
. -, CommandBuilder

10

377

, SQL-
UPDATE, DELETE INSERT.
, CommandBuilder ,
. CommandBuilder , CommandText
Command
Parameter.
CommandBuilder ,
.
ADO, CommandBuilder
. ,
, ADO.
CommandBuilder . , , CommandBuilder ,
. , CommandBuilder . .
.

..,


Data Adapter Configuration Wizard
5 , Data Adapter Configuration Wizard
DataAdapter OLE DB SQL Client
.NET Data Provider. , .
Data Adapter Configuration Wizard ,
. , .
( ?), .
Visual Studio .NET , ( Windows-, Web-. Web- ),
OleDbDataAdapter. Northwind SQL statement
:
SELECT OrderlD, ProductlD, UnltPrice. Quantity
FROM [Order Details]
WHERE OrderlD = ? ORDER BY ProductlD

Next. , . 10-3-

378

Ml : DataSet ADO.NET

view wizard Results


Review the hit of [asks the wizard has pnforried. Click Finish to
zomplete or Back to make changes.

Generated SELECT *.
Generated tabk mssamgs,
SenestKJINSEM ateinert.

. 10-3. View Wizard Results Data Adapter Configuration Wizard

DataAdapter
DataAdapter UPDATE, INSERT
DELETE (. 10-3). Finish . DataAdapter. Properties DeleteCommand . CommandText
. Query Builder DeleteCommand
(. 10-4).

OrderTO
ProdmtlD
Cuiantltv

. 10-4.

[Order Dels
[Order Detj
FCIder Dets

-;

DeleteCommand,

, , Data Adapter Configuration Wizard


, , . ,
Properties InsertCommand UpdateCommand DataAdapter .

10

379


SQL Statement Advanced Options,
, . 10-5. ,
Data Adapter Configuration Wizard.
DataAdapter ,
, Generate Insert, Update And Delete
Statements.
Data Adapter Configuration Wizard
WHERE , , ,
BLOB-. Use Optimistic Concurrency, WHERE .
Advanced SQL Generation Options
Additional Insert, Update, and Delete statements can be generated Co update th* dsta
uj
V 'Generate Insert, Update and Delete statements I
Generates iniert, Update, and Delete statements based on your 5e!ct statement.
'/ IJse optimistic concurrency
Modifies Update and Delete statements to detect whether the database has changed
since the record was loaded into the daEaset TNs helps prevent concurrency conflicts.
'> Refresh the DataSet
Adds a Select statement after Insert and Update (tatements to retrieve identity column
values, drfaufc values, and other values cafcuWed by the database.

. 10-5.

, SQL Server, , . Data Adapter Configuration


Wizard DataAdapter, , Refresh The DataSet. ,
. ,
DataAdapter.Update DataSet
, timestamp .
. , , , .


Data Adapter Configuration Wizard
DataAdapter, SQL Server . Choose A Query Type
Use Existing Stored Procedures (. 10-6) Next.

380

Ml : DataSet ADO.NET

should the date .adapter access the. dal abase'


'' lite SQL wernent*
Spedv a Selesi * tg-lpad <ieia, and the -card wil generate Ihe Inset, Update,
end Dfitto sUlwwnti ID if- ddla changes.
<'

fffrtrnew jDrcdprocedure

Choose er. *risif g oied pfOure for each opeuten (tat. !, update snd
It},

. 10-6. Choose A Query Type Data Adapter Configuration Wizard


Command
DataAdapter . SelectCommand. (. 10-7).
.
SOaia ftdaplei ConllgUfalim Wizard
find Commands to Existing Stored Procedures
Choose
tfie
riotedprasziU'sscacJenLJscedVaiY'eoj''

. 10-7.

SelectCommand DataAdapter

SelectCommand, InsertCommand UpdateCommand DataAdapter.


SourceColumn , (. 10-8).
Data Adapter Configuration Wizard
SourceVersion Parameter. Current, Properties , .

10

381

Bind Commands to Existing Stared Procedures

a scored far each **. If arocedu


hfch tmif* data row nrtains the Set Irtr( oraeedur; parameters
I Pe-am*f

Source Cofcjrm

jeOraerl!}

i^Produd^D

ProdutilC

i@Quanl4r

Quanttv

jiJUntPrite

Lntf-bie

. 10-8. SourceColumn
InsertCommand
Visual Studio .NET Enterprise Edition, SQL-, Data Adapter Configuration Wizard
SQL Server SelectCommand. UpdateCommand,
InsertCommand DeleteCommand DataAdapter. Choose A Query
Create New Stored Procedures;
SQL-, (. 10-9).
atB Aiplpr Canfieurniion
Generate the stored procedures
The Stlt stemeni Mil bg used to male th Meet. , Update
id Mete stored t*xedures.
Tycein vour a^3etelstetTient-B1^ttw>jefy Mder to^ep^all/
hit dtBihouU)lh= data adapter toad info the dalasrt?
5ELECI
-- .
?roductlDp

ftdwnted Opt

. 10-9-

SQL-


. , Preview SQL Script, SQL-, Data Adapter
Configuration Wizard
( 10-10). ,
SQL- , .

382

III

: DataSet .NET

SET W;
SELECT OKierta o-MucllO ?.-*-:-. Unltfritt FfiOMfOrder Details] WHERE
- (OtdsHD - --) O4XR BV =-(rfucSP;

IM5EBT INTO[OrdH E><*] (OntotlD,


. DriterlO, ProdutllD, IjHrHh', LN(P" FRCrt J5rdw W*^
MtRE (OrdwlD . pOrdjrlC) *NO (Produc:ID - JProBultES OCS!
ProdutllP;
S^ve As, . ;

ppy**

. 10-10. SQL-,


DataAdapter .


, Data Adapter Configuration
Wizard , . , CommandBuilder. , , .
, CommandBuilder, ,
, .
, , CommandBuilder.
, Data Adapter Configuration Wizard .
Visual Studio .NET DataAdapter OLE
DB SQL Client .NET Data Provider. ,
. Command,
, , DataAdapter
. , , Data
Adapter Configuration Wizard .


, DataSet. 1 ( INSERT, UPDATE DELETE
), ,
.

10

383

, ,
, ? NULL
? ?
TableMappings DataAdapter ?
, ,


.
,
.
, . ? .
.

SQL- UPDATE DELETE ; .
. ,
. . ,
, , .
:

;
;
;
, , .

,
.
, ,
. , .
Data Adapter Configuration Wizard, CommandBuilder
.
Advanced Options Use Optimistic
Concurrency.
WHERE
, * ? , .

384

III : DataSet ADO.NET

.
CommandBuilder Data Adapter Configuration
Wizard WHERE .
,
, , , .
. ,
. ContactName .
WHERE , UPDATE :
UPDATE Customers
SET CustomerlD = 'ABCDE', CompanyName = 'Original Company Name',
ContactName = 'New Contact', Phone = '600-555-1212'
WHERE Customer-ID = 'ABCDE' AND
CompanyName = 'Original Company Name' AND
ContactName = 'Original Contact' AND
Phone = '800-555-1212'

CompanyName
. , ContactName . UPDATE
;
UPDATE Customers
SET CustomerlD = ' A B C D E ' , CompanyName
ContactName = 'Original Contact',
WHERE CustomerlD = 'ABCDE' AND
CompanyName = 'Original Company
ContactName = 'Original Contact'
Phone = 'BOO-555-1212'

= 'New Company Name',


Phone = '800-555-1212'
Name' AND
AND

ContactName ,
WHERE. ,
. DataAdapter ,
, , , DataRow.
11.
CommandBuilder. Data Adapter Configuration Wizard .
, -.
- , - ,
. mandBuilder Data Adapter Configuration Wizard
- WHERE .
.

10

385

timestamp
timestamp WHERE . SQL Server timestamp
, , .
SQL Server timestamp,
SQL Server
timestamp . Customers timestamp
;
UPDATE Customers
SET CustomerlD = ' A B O D E ' , CompanyName = 'Original Company Name',
ContactName = 'New Contact', Phone = '800-555-1212''
WHERE CustomerlD = 'ABODE' AND
TimestampColumn = OxOOOOOOOOOOOOOOCC


timestamp, WHERE timestamp
, .
. , /. , , .
CommandBuilder, Data Adapter
Configuration Wizard
.
SQL Server 2000 rowversion timestamp , SQL Server
rowversion. timestamp. timestamp
,
.

timestamp, ,
.

ADO WHERE . , SET UPDATE .
, . , . CompanyName, ContactName.
ContactName. UPDATE :

386

III

: DataSet ADO.NET

UPDATE Customers
SET ContactName = 'New Contact'
WHERE Customer-ID = 'ABCDE' AND

ContactName = 'Original Contact'

CompanyName
UPDATE:
UPDATE Customers
SET CompanyName = 'New Company Name'
WHERE Customer-ID = 'ABCDE' AND

CompanyName = 'Original Company Name'



CustomerlD

CompanyName

ContactName

ABCDE

Original Company Name

Original Contact

CustomerlD

CompanyName

ContactName

ABCDE

Original Company Name

New Contact


CustomerlD

CompanyName

ContactName

ABCDE

New Company Name

New Contact

, , .
DataAdapter ADO.NET ,
, , .
DataAdapter
, .
, Command,
RowUpdating DataAdapter. , , .

NULL
Customers Northwind Region, 15
, NULL. Region NULL. :
SELECT CustomerlD, CompanyName, ContactName, Phone
FROM Customers WHERE Region = NULL

10

387

ADO.NET SQL QueryAnalyzer, , .


NULL ,
. ANSI, NULL = .
IS NULL. Customers,
Region NULL:
SELECT Customer-ID, CompanyName, Contact Name,

Phone

FROM Customers WHERE Region IS NULL

NULL
DataAdapter? Commandlext
Command,
Order Details;
UPDATE [Order Details]
SET Order-ID = ?, ProductID = ?, Quantity = ?, UnitPrice = ?
WHERE OrderlD = ? AND ProductID = ? AND
Quantity = ? AND UnitPrice = ?

NULL. , WHERE . ,
Quantity UnitPrice ? , Quantity, NULL, 20, , :
UPDATE [Order Details]
SET OrderlD = 12345, ProductlD = 1, Quantity = 20, UnitPrice = 18
WHERE OrderlD = 12345 AND ProductID = 1 AND
Quantity = Null AND UnitPrice = 18

- Quantity = Null, WHERE, . Quantity Null,


Null = Null false, ,
WHERE
NUJ^L ?
NULL,
ColumnName = ?

(ColumnName = ? OR ((ColumnNarne IS NULL) AND {? IS NULL)))

, true,
, NULL NULL.
, DataAdapter Customers
CustomerlD, Company-Name, ContactName Phone. CustomerlD CompanyName
, ContactName Phone NULL. , WHERE
NULL. -

388

111 : DataSet ADO.NET

Data Adapter Configuration Wizard, ,


NULL:
UPDATE Customers
SET Customer-ID = ?, CompanyName = ?, ContactName = ?, Phone = ?
WHERE (Customer-ID = ?} AND (CompanyName = ?) AND
{ContactName = ? OR ((? IS NULL) AND (ContactName IS NULL)))
AND (Phone = ? OR ((? IS NULL) AND (Phone IS NULL)))

, Data Adapter Configuration Wizard


.
, , .


,
, . .
DataAdapter Transaction.
DataAdapter . Command, UpdateCommand. InsertCommand DeleteCommand. Command Transaction,
DataAdapter Transaction Command, DataAdapter,
:
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSOK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " &
"FROM [Order Details] WHERE OrderlD = 10503 " & _
"ORDER BY ProductID"
Dim tbl As New DataTableO
Dim en As New OleDbConnection(strConn)
Dim da As New OleDfaOataAdapterfstrSQL, en)
'Define updating logic for the DataAdapter.
'
.0()
da.Fill(tbl)
' DataTable
'
Dim txn As OleDbTransaction = cn,BeginTransaction()
' Transaction Command,
' DataAdapter

10

389

da.UpdateComitiand.Transaction = txn
da.InsertCommand.Transaction = txn
da.DeleteCommand.Transaction = txn
'
da.Update(tbl)
'
txn.Commit()
cn.Close()

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SGLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " +
"FROM [Order Details] WHERE OrderlD = 10503 " +
"ORDER BY ProductID";
DataTable tbl = new DataTableO;
DleDbConnection en = new OleDbConnection(strConn);
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, en);
//Define updating logic for the DataAdapter.
//
.;
da.Fill(tbl);
// DataTable
//
OleDbTransaction txn = cn.BeginTransactionO;
// Transaction Command,
// DataAdapter
da.UpdateCommand,Transaction = txn;
da.InsertCommand.Transaction = txn;
da.DeleteCommand.Transaction = txn;
//
da.Update(tbl);
//
txn.CommitO;
cn.CloseO;
CommandBuilder,
. CommandBuilder .
, DataAdapter Update.
CommandBuilder, ,

390

III ; DataSet ADO.NET

ADO.NET :
Visual Basic .NET
Dim strConn, strSQL As String

Dim tbl As New DataTable()


Dim en As New 01eDbConnection{strConn)
Dim da As New 01eDbDataAdapter(strSQL, en)
Dim cb As New OleDbCommandBuilder(da)
cn.OpenO
da.Fill(tbl)
Dim txn As OleDbTransaction = en.Begin!ransaction()
da.Update(tbl)
txn.CommitO

cn.Close()
Visual C# .NET
string strConn, strSQL;
DataTabLe tbl = new DataTableC);
OleDbConnection en = new OleDbConnection(strConn);
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, Cn);
OleDbCommandBuilder cb = new QleDbCommandBuilder(da);
cn.OpenO;
da.Fill(tbl);
OleDbTransaction txn = cn.BeginTransaction();
da.Update(tbl);
txn.CommitO;
cn.CloseO;
DataAdapterL'pdate CommandBuilder
, SelectCommand DataAdapter.
Command SelectCommand . , CommandBuilder , .
Update DataAdapter , :
da.SelectCommand.Transaction = txn

, CommandBuilder . , . CommandBuilder
, mandBuilder.GelUpdateCommand ( GetlnsertCommand, GetDeleteCommand),
, , CommandBuilder Command Transaction, DataAdapter
:

10

391

Visual Basic .NET


Dim strConn, strSQL As String
Dim tbl As New DataTable()
Dim en As New OleDbConnection(strConn)
Dim da As New 01eDbDataAdapter(strSQL, en)
Dim cb As New OleDbCommandBuilder(da)
en.Open()
cb,GetUpdateCommand()
da.Fill(tbl)
Dim txn As OleDbTransaction = en.Begin!ransaction()
cb.GetUpdateCommand.Transaction = txn
cb.GetlnsertCommand.Transaction = txn
cb.GetDeleteCommand.Transaction = txn
da.Update(tbl)
txn.Commit()
cn.Close()

Visual C# .NET
string strConn, strSQL;
DataTable tbl = new DataTableO;
OleDbConnection en = new OleDbConnection(strConn);
OleDbDataAdapter da = new 01eObDataAdapter(strSQL, en);
OleDbComroandBuilder cb = new OleDbCommandBuilder(da);
cn.0pen();
cb.GetUpdateCommandO;
da.Fill(tbl);
OleDbTransaction txn = en. BeginTransactionO;
cb.GetUpdateComniandC).Transaction = txn;
cb.GetlnsertCommandO. Transaction = txn;
cb. GetDeleteCommandO.Transaction = txn;
da.Update(tbl);
txn.CommitO;

cn.Close();

TableMappings
5 , TableMappings DataAdapter , DataAdapterftil DataSet.
DataAdapterFill DataTable, TableName
Table:
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " &

392

III : DataSet ADO.NET

"FROM [Order Details] WHERE OrderlD = 10503 " & _


"ORDER BY ProductlD"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New DataSet()
da.Fill(ds)

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT OrderlD, ProductlD, Quantity, UnitPrice " +
"FROM [Order Details] WHERE OrderlD = 10503 " +
"ORDER BY ProductlD";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
DataSet ds = new DataSetO;
da.FillCds);

DataTable Order Details,


. -, TableName Fill.
Visual Basic .NET
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New DataSetO
da.Fill(ds, "Order Details")
Visual C# .NET
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
DataSet ds = new DataSetO;
da.Flll(ds, "Order Details");
-, TableMappings DataAdapter, , DataTable Order Details:
Visual Basic .NET
Dim da As New 01eDbDataAdapter(strSQL, strConn)
da.TableMappings.Add("Table", "Order Details")
Dim ds As New DataSetO
da.Fill(ds)

Visual C# .NET
OleDbDataAdapter da = new 01eDbDataAdapter(strSOL, strConn);
da.TableMappings.Add("Table", "Order Details");

10

393

DataSet ds = new DataSetO;


da.Fill(ds);

TableMappings . DataAdapter.Update DataSet, DataAdapter


TableMappings , DataTable DataSet :
Visual Basic .NET
Dim da As New 01eDbDataAdapter{strSQL, strConn)
da,TableHappings.Add("Table", "Order Details")
'
Dim ds As New DataSetO
cJa.Fill(ds)
'
da.Update(ds)

Visual C# .NET
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
// ..
da.TableMappings.Add("Table", "Order Details");
DataSet ds = new DataSetO;
da.Fill(ds);
//
da.Update(ds);
TableMappings DataAdapter ,
Update, DataSet , Update,
DataTable:
Visual Basic .NET
Dim da As New QleDbDataAdapter(strSQL, strConn)
'
Dim ds As New DataSetO
da.FilKds, "Order Details")
'
da.Update{ds, "Order Details")

Dim da As New 01eDbDataAdapter(strSQL, strConn)


'
Dim tbl As New DataTableC)
da.Fill(tbl)
'
da.Update(tbl)

394

III : DataSet ADO.NET

Visual C# .NET
QleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
//
DataSet ds = new DataSetQ;
da,Fill(ds, "Order Details");
//
da.Updatefds, "Order Details");

//

OleDbDataAdapter da = new 01eDbOataAdapter(strSQL, strConn);


//
DataTable tbl = new DataTableO;

da.Fill(tbl);
//
da.Update(tbl);
, DataTable, DataAdapterFill DataAdapterlJpdate, .


ADO.NET . mandButtder. , INSERT, UPDATE DELETE . , Data Adapter Configuration
Wizard, .
?
. ,
DataAdapter .
, Microsoft Access,
, . INSERT, UPDATE DELETE. .
, . , (INSERT,
UPDATE DELETE). , .
Data Adapter Configuration Wizard, , .
- , :
Comm-andBuilder .

10

395

,
. ?
DataSet, , ? ? ADO.NET ? .

OleDbCommandBuilder
CommandBuilder ADO.NET, ,
OleDbCommandBuilder.
CommandBuilder . OleDbCommandBuilder SqlCommandBuilder . ADO.NET
CommandBuilder ,
, ,' , .
CommandBuilder , 7 , CommandBuilder
.NET, mandBuilder , .NET CommandBuilder
,

OleDbCommandBuilder
. 10-1 CommandBuilder.
10-1.

CommandBuilder

DataAdapter


DataAdapter

QuotePrefix

String

QuoteSuffix

String

DataAdapter.
CommandBuilder
,
CommandBuilder
,
CommandBuilder

DataAdapter
DataAdapter CommandBuilder DataAdapter. CommandBuilder.
CommandBuilder,
QuotePrefix QuoteSuffix
QuotePrefix QuoteSuffix -,
CommandBuilder . .

396

III : DataSet ADO.NET

OleDbCommandBuilder
. 10-2 CommandBuilder.
10-2. CommandBuilder

DeriveParatneters
GetDeleteCommand
GetlnsertCommand
GetUpdateCotnmand
RefreshScbema

Command,
Command
DeleteComtnand DataAdapter
Command
InsertCommand Data/\dapter
Command
UpdateCommand DataAdapter
CommandBuilder )'

DeriveParameters
CommandBuilder
DataAdapter, .
CommandBuilderDerivePdrameters
:
Visual Basic .NET
Dim strConn As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
Dim cmd As New 01eDbCommand("CustOrdersOrders", en)
cmd.CommandType = CommandType.StoredProcedure
Dim cb As New 01eDbCommandBuilder()
cn,0pen()
cb.OeriveParameters(cmd)
cn.CloseO
Dim param As OleDbParameter
For Each param In cmd.Parameters
Console.WriteLine(pa ram.ParameterName)
Console.WriteLine(vbTab & param.Direction.ToString)
Console.WriteLine(vbTab & param.OleDbType.ToStrtng)
Console. WriteLineO
Next param
Visual C# .NET
string strConn;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
OleDbCommand cmd = new OleDbCommandC'CustOrdersOrders", en);

10

397

cmd.ComrnandType = CommandType.StoredProcedure;
OleDbCommandBuilder cb = new 01eDbCommandBuilder();
cn.OpenO;
cti.DeriveParameters(cmd);
cn.Close();

foreach {OleDbParameter param in cmd.Parameters)

{
Console.WriteLine{pa ram,ParameterName);
Console. WriteLine("\t" + param. Direction. ToStringO);
Console.WriteLine("\t" + param.OleDbType.ToStringO);
Console.WriteLine();

Parameters Command, , , Size,


Precision Size, .
DeriveParameters Connection, Command.
GetDeleteCommand, GetlnsertCommand GetUpdateCommand
GetDeleteCommand, GetlnsertCommand GetUpdateCommand
, CommandBuilder.
, .
CommandBuilder
CommandText ,
CommandBuilder. ,
.

RefreshSchema
,
DataAdapter, , , RefreshSchema CommandBuilder.
CommandText SelectCommand.
DataAdapter, - DataAdapter
. CommandBuilder , , , . ,
DataAdapter }' CommandBuilder , CommandBuilderRefreshSchema.
CommandBuilder . , , . CommandBuilder DataAdapter Update Get<Update/Insert/Delete>Command
CommandBuilder,

398

111 : DataSet AOO.NET

,
. , DataAdapter DataSet
DataSet .
DataAdapter^ , , ,
DataAdapter. ?
. DataSet
DataAdapter,
.
, , DataSet,
DataSet . DataAdapter. DataSet,
)- DataAdapter .
DataAdapter , , ,
SelectCommand,
DataAdapter
Command, . , , DataAdapter
( ),
InsertCommand. DataAdapter
Command, SelectCommand. UpdateCommand DeleteCommand, .
DataAdapter CommandButtder.
,
SelectCommand DataAdapter.
. DataTable
,
DataAdapter.
Data Adapter Configuration Wizard, CommandButtder.
?
. , 7,
.

, , . ,
, , :
SELECT D.OrderlD, P.ProductName, D.ProductID,
D.Quantity, D.UnitPrice
FROM [Order Details] D, Products P
WHERE D.OrderlD = 10503 AND D.ProductID = P.ProductID
ORDER BY P.ProductID

10

399

DataTable , ? . Order Details Data


Adapter Configuration Wizard CommandBuilder .
ADO ,
, .
Recordset ADO , Order Details,
ADO Order
Details.
, , , ProductlD ( Order
Details) ProductName ( Products), ADO ProductlD Order Details ProductName
Products. , .
, ADO, ADO .NET .
Order Details , ProductName.
? CommandBuilder, Data Adapter Configuration Wizard
.
ProductName,
ProductName .
, .
.
DataRelation DataColumn, * 7 , ,
DataTable DataRelation . ,
. DataTable ,
CommandBuilder Data Adapter Configuration Wizard
.
. .
ADO.NET ?
.
. DataSef , ,
DataSet , . ,
, ,
, . -

400

III

: DataSet ADO.NET

,
:
SELECT * FROM [Order Details] HOLDLOCK WHERE OrderlD = 10503

SQL Server 2000.


.
, .
. , Submit Changes
? .
, .
. .
,
, .
. , 1 ,
.
, , (
), . , ,
, . ,
, .
, . .
. .
. , DataSet BLOB-,
?
. , BLOB-, .
, DataAdapter ,
, SET , Commandlext
UpdateCommand, , . , , ( ) , BLOB-. ?
, Employees, , , .
JPEG-.
DataTable
, DataAdapter ,

10

401

, . ,
,
, (. 10-11). DataTable,
DataRelation.
DataTable Employees EmployeelD, LastName
FirstName. DataTable Photo -, EmployeelD, DataTable.
Employees
LastName

EmployeelD

DaDavolio

FirslName
Nancy

Fuller

Andrew

Leverling

Janet

Peacock

Margaret

EmployeesPhatos

EmployeelD

Photo

< Photo>

< Photo

< Photo

< Photo>

. 10-11. DataTable
BLOB-
DataSet
DataTable DataAdapter,
Title ,
Photo. Photo , .
, , ,
.
.
, Order Details
CommandBuilder, < Incorrect
syntax near the keyword 'Order' ( 'Order').
?

402

III

: DataSet ADO.NET

. , ? , .
, .
CommandBuilder
, , - , . mandBuilder ,
, QuotePrefix QuoteSuffix
, . ,
, ? OLE DB .NET Data Provider OleDbConnection.GetOleDbSchemaTable
-. :
OLE DB-, SQL
Server, Oracle Access:
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " & _
"FROM [Order Details] WHERE OrderlD = 10503 " & _
"ORDER BY ProductID"
Dim en As New OleDbConnection(strConn)
Dim da As New 01eDbDataAdapter(strSQL, en)
cn.0pen()
Dim cb As New OleDbCommandBuilder(da)
Dim tblSchema As DataTable
tblSchema = cn.Get01eDbSchemaTable{01eDbSchernaGuld.DbInfoLiterals,
New ObjectQ {})
cn.CloseO
tblSchema,PrimaryKey = New DataColumn{)
{tblSchema.ColumnsC'LiteralName")}
Dim row As DataRow
row = tblSchema.Rows.Flnd("Quote_Prefix")
If Not row Is Nothing Then
cb.QuotePrefix = row("LiteralValue")
End If
row = tblSchema.Rows.Find("Quote_Suffix")
If Not row Is Nothing Then
cb.QuoteSuffix = row("LiteralValue")
End If
Visual C# .NET
string strConn, strSQL;
StrConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +

10

403

"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " +
"FROM [Order Details] WHERE OrderlD = 10503 " +
"ORDER BY ProductID";
OleDbConnection en = new OleDbConnection(strConn);
OleDbDataAdapter da = new 01eDbOataAdapter{strSQL, en);
cn.OpenO;
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
DataTable tblSchema;
tblSchema = cn.Get01eDbSchemaTable(01eDbSchemaGuid.DbInfoLiterals,
new object[] {});
cn.CloseO;
tblSchema.PrimaryKey = new DataColumn[]
{tblSchema.Columns["LiteralName"]};
DataRow row;
row = tblSchema.Rows,Find("Quote_Prefix");
if (row != null)
cb.QuotePreflx = row["LiteralValue"];
row = tblSchema.Rows.Find("Quote_Suffix");
if (row != null)
cb.QuoteSuffix = row["LiteralValue"];
, , .
. DataAdapter ADO.NET,
,
, null. ADO
. ?
. SQL Server
. , DefaultValue DataColumn
ADO.NET ,
ADO.NET > . .
, DEFAULT,
. ADO.NET
DEFAULT.
ADO, ADO.NET, . ADO INSERT ,
. , ,
ADO, , , ADO.NET .
ADO.NET ,
.

11

13 10 , DataAdapter. Data Adapter Configuration Wizard


CommandBuilder. , SQL- UPDATE, UNSERT DELETE, , DataSet, .
10 :

- . , ,
(, timestamp),
, , , ,
, , , , ,
. , timestamp.
, . , . ,
DataSet,
, timestamp DataSet.

11

405

. ,
, . ,
,
. .
,
, , . ,
, .
, -.



10 INSERT, UPDATE
DELETE . , .
, , ,
, . 10,

timestamp Microsoft SQL Server.
. timestamp. .
.
, , OrderDetails Northwind.
timestamp, . .
timestamp. .
, Windows,
Web-. , - . ,

?
, DataAdapter
timestamp UpdateCommand. timestamp.
DataRow, .
, , ,
, . timestamp.
- DataRow,
.

406

III

: DataSet ADO.NET

timestamp

, Order Details
:
SELECT OrderlD, ProductID, Quantity, UnitPrice, TimestampColumn
FROM [Order Details] WHERE OrderlD = ?

10. :
UPDATE [Order Details]
SET OrderlD = ?, ProductID = ?, Quantity = ?, UnitPrice = ?
WHERE OrderlD = ? AND ProductID = ? AND TSCol = ?
timestamp, , :
SELECT TSCol FROM [Order Details] WHERE OrderlD = ? AND ProductID = ?

, .
, ?
, ADO.NET .



5 , , DataAdapter.
SELECT CustornerlD, CompanyName, ContactName, Phone FROM Customers;
SELECT OrderlD, CustomerID, EmployeelD, OrderDate FROM Orders

,
. UPDATE ,
timestamp. CommandText UpdateCommand DataAdapter :
UPDATE [Order Details]
SET OrderlD = ?, ProductID = ?, Quantity = ?, UnitPrice = ?
WHERE OrderlD = ? AND ProductID = ? AND TSCol = ?;
SELECT TSCol FROM [Order Details] WHERE OrderlD = ? AND ProductID = ?

, . , Microsoft SQL Server, Oracle Microsoft


Access .
.
, DataAdapter SELECT DataRow.
DataRow timestamp, , .

11

407

UpdatedDataSource Command
DatoAdapter Command, InsertCommand, UpdateCommand DeleteCommand.
DataAdapter InsertCommand UpdateCommand''. UpdatedRowSource
Command,
UpdateRowSource
(. 11-1). Command
,
.
11-1. UpdateRowSource

Both

FirstRetumedRecord

None

OutputParameters

Command ,
.
Command

Command
Command

,
UpdatedDataSource . , Order Details
. UpdatedDataSource, Both.
InsertCommand . , UpdatedDataSource InsertCommand
, None, . 12% .
UpdatedDataSource , Both,
Command , ,
. UpdatedDataSource
Command , ,
.


UpdatedDataSource , .
,
UPDATE Order Details
timestamp :

408
CREATE

III : DataSet ADO.NET


PROCEDURE

spUpdateDetail

(@OrderIDNew int, @ProductIDNew int, @QuantityNew smallint,


laUnitPriceNew money, @OrderIDOrig int, @ProductIDOrig int,
@TSCol timestamp OUTPUT)
AS
UPDATE [Order Details]
SET OrderlD = @OrderIDNew, ProductlD = @ProductIDNew,
Quantity = @QuantityNew, UnitPrice = @UnitPriceNew
WHERE OrderlD = @OrderIDOrig AND ProductlD = ^ProductlDOrig
AND TSCol = ffTSCol;
IF @@ROWCOUNT = 1
SELECT @TSCol = TSCol FROM [Order Details]
WHERE OrderlD = @OrderIDNew AND ProductlD = @OrderIDNew

, , CommandText UpdateCommand , Parameters, Commands


UpdatedRowSource Command QutputParameters Both.
, SELECT.
, . , Oracle , , .

RowUpdated
DataAdapter
, Microsoft Access, ,
, . .
, , .
DataAdapter , , DataRow RowUpdating RowUpdated.
, , .
, RowUpdating Ron-Updated . , :
RowUpdating event fired for row #1
RowUpdated event fired for row #1
RowUpdating event fired for row #2
RowUpdated event fired for row 92
RowUpdating event fired for row 3
RowUpdated event fired for row 83

RowUpdated , . }- RowUpdated. -

11

409

, DataTable, DataAdapter Command


timestamp.
: RotvUpdated , . ,
timestamp . , Command, timestamp, ,
ExecuteScalar.
Visual Basic .NET
Dim da As OleDbDataAdapter = CreateMyDataAdapterQ
Dim cmdGetNewTS As OleDbCommand = CreateGetNewTSCommandO
AddHandler da.RowUpdated, AddressOf HandleRowUpdated
Dim tbl As DataTable = CreateMyDataTableO
da.Fill(tbl)
da.Update(tbl)
Private Sub HandleRowUpdated(ByVal sender As Object,
ByVal e As QleDbRowUpdatedEventArgs)
If e.Status = UpdateStatus.Continue AndAlso
(e.StatementType = StatementType.Insert OrElse
e.StatementType = StatementType.Update) Then
cmdGetNewTS.Parameters("!SOrderID"). Value = e.Row("OrderID")
cmdGetNewTS.Parameters("@ProductID").Value = e,Row("ProductID")
e.How("TSCol") = CTypeCcmdGetNewTS.ExecuteScalar, ByteO)
e.Row.AcceptChanges()
End If
End Sub

Visual C# .NET
OleDbDataAdapter da = CreateMyDataAdapter{);
OleDbCommand cmdGetNewTS = CreateGetNewTSCommandO;
da.RowUpdated += new OleDbRowUpdatedEventHandler(HandleRowUpdated);
DataTable tbl = CreateHyDataTableO;
da.Fill(tbl);
da.Update(tbl);
private void HandleRowUpdated(object sender, OleDbRowUpdatedEventArgs e)
{
if ((e.Status == UpdateStatus.Continue) 8A
((e.StatementType == StatementType.Insert) ||
(e.StatementType == StatementType,Update)))
\
cmdGetNewTS.Parameters["@OrderID"].Value = e.Row["OrderID"];
cmdGetNewTS.Parameters["@ProductID"].Value = e.Row["ProductID"];
e.Row["TSCol"] = (byte[]) cmdGetNewTS.ExecuteScalarO;

410

III

: DataSet AOO.NET

.Row.AcceptChangesC);

timestamp
DataRow, DataRowAcceptChanges .
AcceptCbanges DataRotr , . , timestamp. AcceptChanges, ADO.NET DataRow .
, ;
.
timestamp
35% 50%
.

Timestamp
- Timestamp ( Visual
Basic .NET Visual * .NET), (. 11-1).
: timestamp, .

Ifi-fresfningafter update Id reirieve new timestamp values

Summary1

his sample demonslrales various '"ays refreshing dala in a row alter submitting updates.
When you click any ol the buttons below, the code will run a test lhal adds a new row to a table- that
:ontains a timestamp column.

The lest wil then modify the contents ol the DataRow and try to submil lhal change to the database, li
i the update succeeds, the test w<l then try ID delete the rnw Irorn the database

j In each lest, the OataAdapler relies on the tade's primary key and timestanp values ID enforce- optimistic
^concurrency II the DataRow obiecl does not contain the limestamp value that currently resides in the
^database, then the update attempl will fail

Normal

Retrieving new Imestaup values through stored procedures output parameters

arched Gueiy por

nsert succeeded!
Update succeeded!
Ddete succeeded!

. 11-1.

Timestamp


SQL Server, Access, Sybase ,
IDENTITY (IDENTITY columns). -

11

411

, . Northwind, Employees. Orders Products,


.

? ,
. , .
, ,
ADO.NET
?

SQL Server
,
DataAdapter, ,
Northwind Orders :
SELECT OrderlD, CustomerlD, EmployeelO, OrderDate FROM Orders

:
INSERT INTO Orders (CustomerlD, EmployeelD, OrderDate) VALUES (?, ?, ?)
, ,
:
SELECT etIDENTITY

, ?
, @@IDENTITY SCOPEJDENTITY.
.
ADO.NET ,
, timestamp.
CommandText InsertCommand
DataAdapter SELECT @@IDENTITY :
INSERT INTO Orders (CustomerlD, EmployeelD, OrderDate) VALUES (?, ?, ?);
SELECT ^IDENTITY AS OrderlD

: SELECT @@IDENTITY , Command, .


timestamp, :
CREATE PROCEDURE spOrdersInsert
(@OrderID int OUTPUT, ^CustomerlD nchar(5),
@EmployeeID int, eOrderDate datetime)
AS
INSERT INTO Orders (CustomerlD, EmployeelD, OrderDate)

412

III

: DataSet ADO.NET

VALUES (@CustomerID, @EmployeeID, @OrderDate)


SELECT @OrderID = IDENTITY

, RowUpdated DataAdapter
, :
Visual Basic .NET
Dint da As OleDbDataAdapter = CreateMyDataAdapterQ
Dim en As OleDbConnection = da.SelectCommand.Connection
Dim cmdGetldentity As New 01eDbCommand("SELECT ^IDENTITY", en)
AddHandler da.RowUpdated, AddressOf HandleRowUpdated
Dim tbl As DataTable = CreateHyDataTableO
da.Fill(tbl)
da.Update(tbl)

Private Sub HandleRowUpdated(ByVal sender As Object,


ByVal e As OleDbRowUpdatedEventArgs)
If e.Status = UpdateStatus.Continue AndAlso
e.StatementType = StatementType.Insert Then
e.Row("OrderID") = CType(cmdGetIdentity.ExecuteScalar, Integer)
e. Row.AcceptChangesO
End If
End Sub

Visual C# .NET
OleDbDataAdapter da = CreateHyDataAdapterO;
OleDbConnection en = da.SelectCommand.Connection;
OleDbCommand cmdGetldentity = new OleDbCommandC"SELECT ^IDENTITY", on);
da.RowUpdated += new OleDbRowUpdatedEventHandler(HandleRowUpdated);
DataTable tbl = CreateMyDataTableO;
da.Fill(tbl);
da.Update(tbl);
private void HandleRowUpdated(object sender, OleDbRowUpdatedEventArgs e)
if ((e.Status == UpdateStatus.Continue) &&
((e.StatementType == StatementType.Insert))
e.Row["OrderID"] = (int) cmdGetldentity.ExecuteScalarO;
e.Row.AcceptChanges();

:
, timestamp
RowUpdated, . ,
, .
. ?

11

413

, timestamp. , , RowUpdated .
@@ IDENTITY SCOPEJDENTITY
SELECT @@IDENTITY IDENTITY, . ,
.
, .
. (. 11-2),

. 11-2.


? , ,
, 11-2, .
Orders SELECT @@IDENTITY,
,
.
: SELECT @@IDENTITY , .
SQL Server 2000 : SCOPE__IDENTITY().
SELECT SCOPE_IDENTITY(),
, Orders.
SQL Server Microsoft Desktop Engine (MSDE) 2000
, SCOPEJDENTITY IDENTITY.
.

, SCOPE_IDENTITY() Null. ,

414

III

: DataSet ADO.NET

.
, .
@@IDENTITY SCOPEJDENTITY - SQL Server Books
Online.

Access 2000
Access SELECT @@IDENTITY. 4 OLE DB Jet Provider Access 2000
. SQL Server, Access SELECT @@IDENTITY , .
Access QueryDef , . OLE DB
Jet Provider . ,
RowUpdated DataAdapter, .

Oracle
Oracle , (sequence). SQL Server , SQL Server . Oracle .
, ,
.
Oracle , .
Oracle:
CREATE SEQUENCE MySequence

Oracle , , .
Oracle.
INSERT SELECT,
. Oracle.
. -,
INSERT
INSERT INTO NyTable (ID, Other-Column)
VALUES (MySequence.NEXTVAL, 'New Row')


.
:

11

415

SELECT MySequence.CURRVAL FROM DUAL

SELECT @@IDENTITY Access SQL Server,


, , .
DataRow? Oracle
, ,
CommandText InsertCommand Sequence.CURRVAL RowUpdated
DataAdapter :
Visual Basic .NET
Dim da As OleDbDataAdapter = CreateMyDataAdapter()
Dim en As OleDbConnection = da.SelectCommand,Connection
Dim strSQL As String = "SELECT HySequence.CURRVAL FROM DUAL"
Dim cmdGetSequence As New 01eDbCommand(strSQL, en)
AddHandler da.RowUpdated, AddressOf HandleRowUpdated
Dim tbl As DataTable = CreateMyDataTableO
da.Fill(tbl)

da.Update(tbl)
Private Sub HandleRowUpdated(ByVal sender As Object,
ByVal e As OleDbRowUpdatedEventArgs)
If e.Status = UpdateStatus.Continue AndAlso
e.StatementType = StatementType.Insert Then
e.Row("OrderID") = CType(cmdGetSequence.ExecuteScalar, Integer)
e.Row.AcceptChangesC)
End If
End Sub

Visual C# .NET
OleDbDataAdapter da = CraateHyDataAdapterO;
OleDbConnection en = da,SelectCommand.Connection;
string StrSQL = "SELECT MySequence.CURRVAL FROM DUAL";
OleDbCommand cmdGetSequence = new 01eDbCommand(strSQL, en);
da.RowUpdated += new OleDbRowllpdatedEventHandler(HandleRowUpdated);
DataTable tbl = CreateHyDataTableO;
da.Fill(tbl);
da.Update(tbl);
private void HandleRowUpdated(object sender, OleDbRowUpdatedEventArgs e)
{
if ((e.Status == UpdateStatus.Continue) &&
. StatementType == StatementType.Insert))
{
e.Row["OrderID"] = (int) cmdGetSequence.ExecuteScalarO;

416

lit

: DataSet ADO.NET

e.Row.AcceptChangesO;

}
I

INSERT INTO Sequence.NEXTVAL


INSERT
INTO. ,

.
INSERT INTO.
CREATE PROCEDURE MyStoredProc
(pOtherCol IN VARCHAR2, pID OUT NUMBER) IS
BEGIN
SELECT MySequence.NE)CTVAL INTO pID FROM DUAL;

INSERT INTO MyTable (ID, OtherCol)


VALUES (pID, pOtherCol);
END;

. InsertCommand DataAdapter, .
DataRow, DataRow .
:
.
.
, , . , ,
.
DataColumn

,
Autolncrement DataColumn True,
ADO.NET .
. . DataAdapterfillSche Data Adapter Configuration Wizard, ADO.NET , .

DataAdapter. CommandBuilder Data Adapter Configuration
Wizard , , InsertCommand, . -

11

417

, .
, . . , ,
, ,
.
, , Oracle, DataSet , ADO.NET .
Microsoft .

,
, DataSet.
SQL Server ,
RoivUpdated DataAdapter, Access Ron-Updated DataAdapter,
Oracle RowUpdated DataAdapter. .
- ( Visual Basic
,NET Visual * .NET), , . . 11-3 , AutolncrementSql. , - , Access, Oracle.
* iMriiiving auto-increment waltiss from SQL Server
Summary
[this sample demonstrate various ways of retrieving newly generated auto-increment values Irom a SQL
iServer database
When you click any of the buttons below. I he codswil run a test that adds new rows to a DalaTabls
|and then submits those new rows to your database
The lest will display the contents of the auto-inciement column for each row in the DalaTabteboth
^before and after submitting the new rows to your database.
Each lest re-sets the contents of Ihe lest table ki your database and inserts two initial lows As a result,
fyoui new rows should have auto-inciement values of 3.4. and 5.
Resutts:
Relrievng new aulo-hcrement values through stored procedure output parameter
! iBefore submitting new rows to database:
Batched QueryFa
j
First new row ID --1
Second new row ID--2
Third new row ID = -3
Alter submitting new tows lo database
Fhstnew row ID -3
Second new row ID = 4
Third new row ID = 5

. 11-3.

AutoIncrementSql

41 8

III : DataSet ADO.NET


NOCOUNT SQL Server
/
. , , :
CREATE PROCEDURE spQrderlnsert
(OrderID int OUTPUT, SCustomerlD nchar(5),
Employee3D int, ^OrderDate datetime)
AS
INSERT INTO Orders (CustomerlD, EmployeelD, OrderDate)
VALUES (@CustomerID, EmployeelD, @OrderDate)
SELECT @OrderID = SCOPE_IDENTI7Y()
INSERT INTO OrdersLog (TypeOfChange, DateOfChange)
VALUES (OrderID + ' added', GetDateO)
RETURN

InsertCommand DataAdapter, . . , .
, ,
:
CREATE PROCEDURE spOrderUpdate
(@CustomerID_New nchar(5), @EmployeeID_New int,
@GrderOate_New datetime, @>OrderID_Orig int,
@CustomerID_Orig nchar(5), @EmployeeID_Orig int,
@OrderDate_Orig datetime)
AS
UPDATE Orders
SET CustomerlD = @CustomerID_New, EmployeelD = @EmployeeID_New,
OrderDate = @OrderDate_New
WHERE OrderlD = @OrderID_Orig AND CustomerlD = 9CustomerID_Orig
AND EmployeelD = @EmployeeID_Orig AND OrderDate = @OrderDate_Orig
IF @@ROWCOUNT = 1
INSERT INTO OrdersLog (TypeOfChange, DateOfChange)
VALUES ('Modified order ' + @OrderID_Orig, GetDateO)
ELSE
INSERT INTO OrdersLog (TypeOfChange, DateOfChange)
VALUES (Tailed to modify order ' + @OrderID_Orig, GetDateO)
RETURN

SQL Server Query Analyzer ,


Results:
(1 row(s) affected)
(1 row(s) affected)

11

419

? ,
WHERE UPDATE , . , , , .
, Command ADO.NET . ExecuteNonQuery 2.

, , , , , .
, , ,
. ADO.NET ,
DataAdapter , ,
, . , .
, UpdateCommand
DataAdapter, , .
NOCOUNT SQL Server ,
. UPDATE SET NOCOUNT ON SQL Server QueryAnalyzer, :
The command(s) completed successfully.

, ,
. , , ,
, .
, , , UpdateCommand DataAdapter , DataAdapter , .
<row(s) affected , . SET NOCOUNT ON UPDATE, :
CREATE PROCEDURE spOrderUpdate
(@CustomerID_New nchar(5), @EmployeeID_New int,
@OrderOate_New datetime, @OrderID_Orig int,
@CustomerID_Orig nchar(5), @EmployeeID_Orig int,
@QrderDate_Orlg datetime)
AS
UPDATE Orders
SET CustomerlD = @CustomerID_New, EmployeelD = EmployeeID_New,
OrderDate = @OrderDate_New
WHERE OrderlD = ig>OrderID_Orig AND CustomerlD = @CustomerID_Orig
AND EmployeelD = @EmployeeID_Orig AND OrderDate = OrderDate_Orig
SET NOCOUNT ON

420

III : DataSet ADO.NET

IF @@ROWCOUNT = 1
INSERT INTO OrdersLog (TypeOfChange, DateOfChange)
VALUES ('Modified order ' + @QrderID_Orig, GetDateQ)
ELSE
INSERT INTO OrdersLog (TypeOfChange, DateOfChange)
VALUES (Tailed to modify order ' + @OrderID_Orlg, GetDateO)
RETURN

UPDATE , :
CREATE PROCEDURE MyUpdateProcedure
( . . . ) AS

SET NOCOUNT ON

INSERT INTO HyLogTable , . ,


SET NOCOUNT OFF
UPDATE MyTable SET ...
RETURN

, DataAdapter , InsertComtnand, UpdateCommand DeleteCommand, CommandExecuteNonQuery.


, , ? , ?


DataSet,
. .

,
, , . . .
DataSet
. , DataSet ,
.
, , . :
Northwind ,
.
DataSet ,
. , .

11

421

. Northwind
, , .
.
, . Northwind ,
Order Details.
, , .

Visual Basic .NET


CustoiersAdapter.Update(MyDataSet.Tables("Customers"))
QrdersAdapter.Update(KyDataSet.Tables("Orders"))

Visual C# .NET
CustoinersAdapter.Update{MyDataSet.Tables["Customers"]);
OrdersAdapter.Update(HyDataSet.Tables["Orders"]);
, '
, DataAdapter, Orders, , , .

Visual Basic .NET


OrdersAdapter.Update(MyDataSet.Tables("Orders"))
CustomersAdapter.Update(MyDataSet.Tables("Customers"))

Visual C# .NET
OrdersAdapter.Update(HyDataSet.Tables["Orders"]>;
CustoniersAdapter.Upciate(MyDataSet.Tables["CiJstomers"]);
? , DataSet
:
1. ;
2. ;
3. ; i
4- ;
5. ;
6. .

Select DataTabfe
7, DataTable.Select
DataRow, . , DataRow, ,

422

III

: DataSet ADO.NET

City Seattle. ContactName.


tbl.Select("City = 'Seattle'", "ContactName", DataViewRowState.Added)

Select DataRow,
DataAdapter.update . !
Select
:
Visual Basic .NET
Dim
Dim
Dim
Dim
Dim

ds As OataSet = CreateDataSetO
tblCustomers As DataTable = ds.Tables("Customers")
tbldrders As DataTable = ds.Tables("Orders")
daCustomers As OleDbDataAdapter = CreateCustomersAdapterO
daOrders As OleDbDataAdapter = CreateOrdersAdapter()

FillDataSetAndHodifyltsContents(ds)
' , -
daCustomers.Update(tblCustomers.SelectC'", "", DataViewRowState.Added))
daOrders.UpdateCtblOrders.Selectf"", "", DataViewRowState.Added))
' , -
daCustomers.Update(tblCustomers.SelectC"", "",
DataViewRowState.ModifiedCurrent))
daOrders.Update(tblOrders.SelectC'", "", DataViewRowState.HodifiedCurrent))
' , -
daOrders.Update(tblOrders.Select("", "", DataViewRowState.Deleted))
daCustomers.Update(tblCustomers.Select("", "", DataViewRowState.Deleted))

Visual C# .NET
DataSet ds = CreateDataSetO;
DataTable tblCustomers = ds.Tables["Customers"];
DataTable tblOrders = ds.Tables["Orders"];
OleDbDataAdapter daCustomers = CreateCustomersAdapterO;
OleDbDataAdapter daOrders = CreateOrdersAdapter{);
FillDataSetAndModifyltsContents(ds);
// , -
daCustomers.Update(tblCustomers.SelectC'", "", DataViewRowState.Added));
daOrders.Update(tblOrders.SelectC'", "", DataViewRowState.Added));
// , -
daCustomers.Update(tblCustomers.SelectC'", "",
DataViewRowState.ModifiedCurrent));
daOrders.Update(tblOrders.SelectC'", "",
DataViewRowState.ModifiedCurrent));

11

423

// , -
daQrders.Update(tblOrders.Select("", "", DataVlewRowState.Deleted}};
daCustomers.Update(tblCustomer5.Select("", "", DataViewRowState.Deleted));

GetChanges
GetChanges DataSet DataTable.
DataTable, DataTable:
tblNewCustomers = tblCustomers.GetChanges(DataRowState.Added)
daCustomers.Update(tblNewCustoniers)
tblNewOrders = tblOrders.GetChanges(DataRowState.Added)
daOrders.Update(tblNewOrders)

-, , Select. .
GetChanges DataSet DataTable, ,
.
Customers Orders . Orders Northwind OrderlD. DataAdapter,
Orders,
OrderlD, DataTable, Update, tblNewOrders. DataTable DataTable tblOrders, OrderlD .
,
.
Select, .
DataAdapter, DataTable, Select DataRoiv.
DataRow DataTable.
DataTable.



DataSet.
Northwind Orders Order Details. . , , .
6, AutoIncrementSeed AutoIncrementStep DataColumn
-1. , DataSet
11-4.

III : DataSet ADO.NET

424

Orders
Order! D

Caste merit)

Emp!oyee!D

OrderData

10268

GROSR

7/30/1996

10785

GftOSR

12/18/1997

-1

GROSR

1/14/2002

-2

GROSR

1/14/2002

Order Details
QrderlO'

ProdustID

Quantity

IjnitPriee

10268

29

10

99,00

10268

72

27.80

10785

10

10

31.00

10785

75

10

7.75

-1

12

18.00

-1

67

24

14.00

-2

22.00

-2

65

21.05

. 11-4. DataSet
,
,
,
. , .
. , Select DataTable , .
.
':* - . ADO.NET
, DataRelation. DataRelation DataSet. DataSet DataRelation,
DataTable Orders Order Details,
DataAdapter
DataTable
(. 11-5).

11

Orders
OrderlD

CustDmeHS

EmpllGyeelO

10268

GRQSR

7/30/1996

10785

GROSR

12/18/1997

120QO

GROSR

1/14/2002

12001

GROSR

1/14/2002

10

99.00

'. '

Order Details

10268

10268

72

10785

10

10785

27.80

10

31,00

10

7.75

18.00

12000
12000

67

24

14.00

12001

22.00

12001

21.05

. 11-5-
}'
DataTable Order Details OrderlD, .
DataRelation,
.


, Windows-, Web-. Web-
DataSet . DataSet.
,
Web-.
Web- DataSet DataAdapter
.

426

Ml : DataSet ADO.NET

!
. Web-, .
, Web-,
.
, ;
. , Web- ,
, Web-? Web-
DataSet. ,
DataSet . DataSet ,
DalaSel Web- i . ?


GetChanges
DataSet DataTable GetChanges.
DataSet.GetChanges DataSet, ,
DataSet.
Web-, , DataSet.GetChanges Web-.
, DataSet.GetChanges
DataSet, ,
. DataSet, GetChanges,
DataSet . , ,
,
. , , DataSet, DataTable ,
DataRelation, DataTable,
DataSet.GetChanges, , DataTable . DataSet
, DataRelation.
, timestamp. . ,
DataAdapter, Web-,

11

427

timestamp.
timestamp . ?
DataSet Web-.
,
DataSet. timestamp DataSet ?
Web- DataSet, , . ,
.
(. 11-6) Web-
DataSet, timestamp,
.
timestamp, DataSet, Web-, DataSet ?
DataSe!
CuslomeilD

Cora pastime

Contacting

TSOol

ALFKI

Alfreds Futterkiste

Maria Anders

>

ANATR

AnaTrujtllo

AnaTrujillo

>

ANONT

Antonio Moreno

Antonio Moreno

>

AROUT

Around the Horn

Thomas Hardy

>

DataSet
Gi. stcrneni)

Company-Name

TSCo!

Alfreds Ftitterkiste

Hw

>

ANATR

>

ANTON

Antonio Moreno

Antonio Moreno

AROUT

Horn

Mew Contact

>

ftUHd

Da/aSef, GeiCtianges Web-

ALFK1

Alfreds Futterkiste

. 11-6.
Web-

III : DataSet ADO.NET

428

Merge DataSet
Aierge DataSet. DataSet DataSet, DataTable DalaRow. . 11-7.
DataTat'le

DataTable

GnkJinnA

f.-o'umnf)

1
82

DI

DataTahie Merge
Column A

Columns

B1

(null)
(nuiEJ
. 11-7-

OolumnC
(null)

(null)

(null)

(null)

C1

(fiul

Merge DataSet

DataSet DataTable
. Merge
DataSet DataSet. DataSet , DataSet. ,
DataSet DataSet.
.
DataSet, DataTable . . 11-8
. DataSet DataTable
. DataTable ID.
Merge DataSet DataSet. DataSet Merge. DataSet.
DataSet.
.
ADO.NET , .
DataSet 1 2. , DataSet , .

11

DataTable
-Kiy

429

DataTable
ID-Key

ColuninA

CoiurnnA

CO

Main

Main

2nd

2nd

Main

Main

2nd

2nd

Main

Main

2nd

2nd

Sate Taufe Merge


ID-Key

. 11-8.

Column A

GDhmiB

ColumnC

2nd

Main

2nd

2nd

Main

2nd

Main

Mafr

(null)

2nd

(null)

2nd

Merge DataSet

: Merge DataSet, . ADO.NET , Column DataSet


DataSet. . 11-8
ID, 1 2.
, Merge,
.
Web- . DataSet.
GetChanges DataSet,
, Web.
Web- , timestanip . , Web timestamp (
) DataSet.
Web- DataSet timestamp.
DataSet (.
), timestamp DataSet (. 11-9).

430

III : DataSet ADO.NET

DataSet
CompanyName

dontaettee

TSCol

ALFKJ

Alfreds Firtterkiste

New Contact

<0 ?

ANATR

AnaTrujttlo

AnaTrujillo

<0 ?

ANTON

Antonio Moreno

Antonio Moreno

<0 ?

AROUT

Around the Horn

New Contact #2

<0 ?

vOustonwiD, =.:

DataSet timestamp, Web-

CustomejID

Name

j Contat'tHame

ALFKI

Altreds Futterkiste

New Contact #1

<Hoeoe ?

AR OUT

Around the Horn

New Contact #2

< ?

TSCol

DataSet DataSet, Wab-

GompanyName

Cor:i],; \-;: >

TSCol

ALFKJ

Alfreds Ftfierkjste

New Coritad #1

< >

ANATR

AnaTrujillo

AnaTrujiilo

<0 >

ANTON

Antonio Moreno

Antonio Moreno

<0 ?

Around ttie Horn

New Contact #2

< >

. 11-9-
DataSet
Visual Basic .NET
Dim objWebService As New WebServiceClassO
Dim dsMain As DataSet = objWebService.GetDataSetO
ModifyDataSetContents(dsMain)
Dim dsChanges As DataSet = dsMain.GetChanges()
dsChanges = objWebService.SubmitChanges(dsCnanges)
dsMain.Herge(dsChanges)

Visual C# .NET
WebServiceClass objWebService = new WebServiceClassO;
DataSet dsMain = objWebService.GetDataSetO;
ModifyDataSetContents(dsMain);
DataSet dsChanges = dsMain.GetChangesO;
dsChanges = objWebService.SubmitChanges(dsChanges);
dsMain.Herge{dsChanges);

11

431

Merge RowState
. ,
DataSet, , timcstamp.
Ron-State - Modified.

, DalaSet, GetCbanges,
, . Web-
DataSet , ADO.NET , .
, , ADO.NET.
Web- , ADO.NET
Roit'State Modified Unmodified.
DataSet Web-. DataSet ADO.NET
Ron-State ,
DataSet Web- ,
DataSet, Web-,
DataSet, RowState . Unmodified,
ADO.NET . , ,
DataSet,
RowState Unmodified,
Merge AcceptChanges DataSet:
Visual Basic .NET
Dim objWebService As New WebServiceClassO
Dim dsMain As DataSet = objWebService.GetDataSetO
ModifyDataSetContents(dsMain)
Dim dsChanges As DataSet = dsMain. GetChangesO
dsChanges = objWebService.SubmitChanges(dsChanges)
dsMain.Merge(dsChanges)
dsMain. AcceptChangesO

Visual C# .NET
WebServiceClass objWebService = new WebServiceClassO;
DataSet dsMain = ObjWebService.GetDataSetO;
ModifyDataSetContents(dsHain);
DataSet dsChanges = dsMain.GetChangesO;
dsChanges = objWebService.SubmitChanges{dsChanges);
dsHain.Merge(dsChanges);
dsMain. AcceptChangesO;
Merge
.
, . ,
, Orders Northwind.

432

: DataSet ADO.NET

,
Web-. , , ,
. , GetChanges Web (. 11-10).
DataSet
OrderlD

CustomerHI

10643

ALFKt

09/22/1997

10692

ALFKI

10/31/1997

EmployeelD

x ,\. ;^Uti|s?pate;\ .

DataSet
Grrjerip

Customer^

10643

AlFKi

09/22/1997

10692

ALFKI

10/31/1997

-t

Aiwi

;:,

-2

Employee ID

7
, .

;;::, -; lfifh-

02/24/2082
.

02/24/2002

;;

DaiaSet, GetGtianges Web-


Ordertp

Customer ID

-1

02/24/2002'

tr - "2

&im

02/24/2002

trnployiielU

::; j! :1\|;

. 11-10. Web-
GetChanges
DataSet, Web-
, . DataSet. Web- . DataSet,
.
. 11-11. DataSet
, , * OrderlD, , Web-, OrderlD? ?
Merge DataSet DataTable. ,
Merge,
. Merge , DataSet, Web, DataSet, -

11

433

. DataSet \Yeb DataSet.


, ,
.
DalaSetc
EmployeelQ

' OrflerCete

GrdetiD

Customer-it)

10643

ALFKI

09/22/1997

10692

ALFKt

10/31/199?

-t

ALf-KI

0&24/2

AIFK1

02/24/2QQ2

-2

DafaSef
OrderlD

EmplsyeeiO"

OrderOaie

12000

ALFKt

02/24/2002

12001

ALFKI

02/24/2002

:|

DataSet , GetChanges Web-


pflerm

-\

OustomerlD

.EmptoyeelD

^ipHpjJ

10643

ALFK!

22/7

10692

ALFKI

10/31/1997

-t

AtFKI

02/24/2002

-2

ALFKI

02/2422

12000

ALFKt

02/24/2002

12001

ALFKI

02/24/2002

. 11-11. DataSet,
Web-, DataSet
Merge

Merge . 11-11.
DataSet OrderlD DataSet. . OrderlD , * OrderlD.
DataSet , DataSet, Web-

434

III : DataSet ADO.NET

. ;) DataTableSelect , RowState Added,


DataSet ,
DataSet, Web-.
Visual Basic .NET
Dim objWebService As New WebServiceClassO
Dim dsMain As DataSet = objWebService.GetDataSetO
ModifyDataSetContents(dsHain)
Dim dsChanges As DataSet = dsMain.GetChangesO
dsChanges = objWebService. SubmitChanges{dsChanges)
' DataSet DataSet,
' Web-, DataSet
' ,
Dim tbl As DataTable = dsMain.Tables("Orders")
Dim row As DataRow
For Each row in tbl.Select("", "", DataRowViewState.Added)
tbl.Rows.Remove(row)
Next row
dsMain.Merge(dsChanges)
dsMain.AcceptChanges 0
Visual C# .NET
WebServiceClass objWebService = new WebServiceClassO;
DataSet dsMain = objWebService.GetDataSetO;
HodifyDataSetContents(dsHain);
DataSet dsChanges = dsMain.GetChangesO;
dsChanges = objWebService.SubmitChangesfdsChanges};
// DataSet DataSet,
// Web-, DataSet
// , 6
DataTable tbl = dsMain.Tables["0rders"];
f reach DataRow row in tbl.Select("", "", DataRowViewState.Added))
tbl.Rows.Remove(row);
dsMain.Merge(dsChanges);
dsMain.AcceptChanges;

DataSet , . ,
.
DataSet

, , .
Merge , ,
,
DataSet , . , , .

11

435

, ? DataSet DataTable . DataSet


, DataSet
. , ,
DataTahle PseudoKey
(. 11-12). , -
. Merge
.
DataSet

QrdefID

CustoniBFtD

Employee ID

OrderOate

10643

ALFKI

09/22/1997

10692

ALFK1

10/31/1997

-1

ALFKI

G2/24/2D02

-2

ALFKI

02/24/2002

PseudoKsy

DataSet. Web-

OrderlO

Gusto me riD

12000

ALFKI

02/24/2002

12001

ALFKI

02/24/2002

EfrtployeelD

DrderDate

"fseudQX&y

DataSet DataSet, Web-


OrderlO

Custamerio

10643

ALFKI

09/22/1997

10692

ALFKI

10/31/1997

12000

ALFKI

02/24/2002

12001

ALFKI

02/24/2002

EmptoyeelD

QrderDate

PseudoKey

. 11-12. (PseudoKey) DataSet




, ? , ;

436

III : DataSet ADO.NET

Visual Basic .NET


Dim objWebService As New WebServiceClass{)
Dim dsMain As DataSet = objWebService.GetDataSetf)
ModifyDataSetContents(dsMain)
Dim dsChanges As DataSet = dsMain.GetChangesC)
dsChanges = objWebService.SubmitChanges(dsChanges)
' Pseudokey
Dim tblMain As DataTable = ds.Tables("Orders")
Dim pkOriginal As DataColumnO = tblHain.PrtmaryKey
tblMain.PrimaryKey = New DataColumnO {tblMain.Columns("PseudaKey")}
Dim tblChanges As DataTable = dsChanges.TablesC'Orders")
tblChanges.PrimaryKey = New DataColumnO {tblChanges.Columns("PseudoKey")}
dsMain.Herge(dsChanges)
'
',
tblMain.PrimaryKey = pkOriginal
dsMain.AcceptChanges()

Visual C# .NET
WebServiceClass objWebService = new WebServiceClass();
DataSet dsMain = objWebService.GetDataSetO;
ModifyDataSetContents(dsMaln);
DataSet dsChanges = dsMain.GetChanges();
dsChanges = objWebService.SubmitChanges(dsChanges);
// Pseudokey
DataTable tblMain = ds.Tables["Orders"];
DataColumn[] pkOriginal = tblHain.PrimaryKey;
tblMain.PrimaryKey = new DataColumn[] {tblHain.Columns["PseudoKey"]};
DataTable tblChanges = dsChanges.Tables["0rders"];
tblChanges.PrimaryKey = new DataColumn[] {tblChanges.Columns["PseucJoKey"]};
dsMain,Merge(dsChanges);
//
//,
tblMain.PrimaryKey = pkOriginal;
dsMain.AcceptChanges();
PseudoKey?
, . ... .

11

437


.
, , ,
, DataSel
DataTable. ,
, Merge
DataSet , . :
ADO.
.
- ComplexHierarchy
.
.
Northwind , , ,
DataSet
DataAdapter, DataTable.Select
(. 11-13). ,
,
, . DataSet
; , DataSet,
GetChanges, . , DataTable , DataSet, .

mple d*wc*islral3s laiious ways

rubrrdtoj 11

< 14 buttons to U the DataSet. o* iti coHei


Note that if yow lubml Ihe changes usrg Ihe "GetOlsnoes 8 Merge" button, you. nain [ijwfiEi w
pes of Hie dors - both ihe gjrul pendlia raws id Ihe succes iblly subnlled ! vnt
tor the QrderlD a*
he uftfe alows you to use a specielind hierarchy that has an added column rn each BalalaBc l-m :
-ricipr*nt values If ^*ou choose the specialized hienrchli you have the option lo is-rJegrale the changes a the
"GetChenges 5 Merge Plus1 whicH. lehes on these added calurmi 13 merge the :-;-;?! lack into ongina
DataSet

. 11-13-

ComplexHierarchy

,
,
.
(globally unique identified, GUID). , , GUID

438

III

: DataSet ADO.NET

, DataTable
,



ADO.NET . DataSet, . ADO.NET DataRou:
DataAdapter.
, , . , , DataAdapter
, . , ADO.NET , .
. DataSet
.
,
, .
.

, . ? , , .


,
, ,
. , .
, 10
. DataAdapter , .
? DataAdapter
?
ContinueUpdateOnError DataAdapter
ContinueUpdateOnError , DataAdapter
. False, . . DataAdapter DBConcitrrencyException. , DataAdapter ! [ , ContinueUpdateOnError
True.
ContinueUpdateOnError - True , DataAdapter .

11

439

HasErrors DataRow
True, RowError .
DataAdapter.Update HasErrors
DataSet DataTable , . , DataSet DataTable DataAdapt'\Update, ,
. . ContinueUpdateOnError , False,
, Update .


. , . , Windows-
DataGrid , .
, .
, , \Vindows DataGrid:
Visual Basic .NET
Try
MyDataAdapter.ContinueUpdateOnError = True
MyDataAdapter.Update{MyDataTable)
If MyDataTable.HasErrors
Dim strMessage As String
strMessage = "The following row(s) were not updated " &
"successfully:"
Dim row As DataRow
For Each row In MyDataTable.Rows
If row.HasErrors Then
strMessage &= vbCrLf & rowf'ID") & " - " & _
row.RowError
End If
Next row
MessageBox.Show(strMessage)
Else
MessageSox.Show("All updates succeeded")
End If
Catch ex As Exception
MessageBox.Show("The following exception occurred:" & vbCrLf & _
ex.Message)
End Try

III : DataSet ADO.NET

440

Visual C# .NET
try

HyDataAdapter.ContinueUpdateOnError = true;
MyDataAdapter.Update(MyDataTable);
if (MyDataTable.HasErrors)
.

string strMessage;
strMessage = "The following row(s) were not updated " +
"successfully: ";
foreach (OataRow row in MyDataTable.Rows)
if (row.HasErrors)
strMessage += "\n\r" + (string) row["ID"] +
row. RowError;
MessageBox.Show( strMessage);

else
MessageBox.ShowC'All updates succeeded");

catch (Exception ex)


I
MessageBox.Show("The following exception occurred: \n\r" +
ex. Message);

, , ,
. , , ,
,
, . 11-14?

ABCDE

ABCDE Inc.

ABCDE

ABCDE Inc.

$100.00

A8CDE

(.

$125,00

. 11-14.

DataRow .
Visual Basic .NET
Dim tbl As DataTable = CreateFillAndModifyTableO
Dim row As DataRow = tbl.Rows(O)
Console.WriteLlne("Current Balance Due: " & row("BalanceDue"))
Console.WriteLinef"Original Balance Due: " & _
row("BalanceDue", DataRowVersion.Original))

11

441

Visual C# .NET
DataTable tbl = CreateFillAndHodifyTableO;
DataRow row = tbl.Rows[0];
Console.WriteLlne("Current Balance Due: " + row["BalanceDue"]);
Console.WriteLine("Qriginal Balance Due: " +
row["BalanceDue", DataRowVersion.Original]);
?



RowUpdated DataAdapter. , DataAdapter ,
,
.
,
DataAdapter DataSet. ConftictAdapter DataAdapter, . . DataTable
ID. ID , , ,
DataSet.
, .
, , Ron-Update DataRow.

Visual Basic .NET


Private Sub HandleRowUpdatecKByVal sender As Object, .
ByVal e As OleDbRowUpdatedEventArgs)
If e.Status = UpdateStatus.ErrorsOccurred AndAlso
TypeOf(e.Errors) Is DBConcurrencyException Then
ConflictAdapter.SelectCommand.Parameters(O).Value = e.Row("ID")
Dim intRowsReturned As Integer
intRowsReturned = ConflictAdapter. Fill(ConfHctDataSet)
If intRowsReturned = 1 Then
e.Row.RowError = "The row has been modified by another user."
Else
e.Row.RowError = "The row no longer exists in the database."
End If
e.Status = UpdateStatus.Continue
End If
End Sub

Visual C# .NET
private void HandleRowUpdated(object sender, OleDbRowUpdatedEventArgs e)
(
if ((e.Status == UpdateStatus.ErrorsOccurred) &&

III : DataSet ADO.NET

442

(.Errors.GetType == typeof(DBConcurrencyException))

{
ConflictAdapter.SelectCommand.Parameters[0].Value = e.Row["ID"];
int intRowsReturned = ConflictAdapter.Fill(ConflictDataSet);
if (intRowsBeturned == 1}
e.Row.RowError = "The row has been modified by another user.";
else
e.Row.RowError = "The row no longer exists in the database.";
e.Status = UpdateStatus,Continue;

Status Continue SkipCurrentRou1, DataAdapter RowError .



DataSet, . , , 11-14.

....
,

. ADO.NET?
, . , DataAdapter , .
DataAdapter DataRow. DataRow,
,
DataAdapter.Update.
DataRow
, , , .
DataSet.Merge

DataSet DataSetMerge. , Merge . , ,
, DataSet.
RowUpdated DataAdapter. , DataSet

11

443

ConflictDataSet. , DataSet
MainDataSet.
MainDataSet ConflictDataSet:
Visual Basic .NET
MainDataSet,Merge(ConflictDataSet, True)

Visual C# .NET
MainDataSet.Merge{ConfllctDataSet, true);

DataRoiv
DataSet. DataRow
DataSet.
DataSet , .
RoivUpdated,
, .
: ,
, , -

.
DataRow , DataRou' Rows DataTable
. RowState DataRow
Added. DataAdapter,
.

Conflicts
- Conflicts (. 11-15), ,
.
DataSet . .
, .
, DataSet,
- ,
DataSet.
DataSet , .
, . , ,
.

444

III : DataSel ADO.NET

"bis sample appicalion is designed to risbwJ bandbig and


Ctc* the buttons al Ihe lop of tf lam 10 cab iOntkl! You
ssdvelhtflx-^ -;ing rhe .:ontiols in the StalUJ pane. Altei vou have

RowState: Modined
RowEtror: The row has been modified V *

Modiliad By Current U
Original Vale
Modified By Currant
Original Value
Original Value

. 11-15.

Conflicts


4 Transaction ADO.NET. , ,
,
, .
, :
UPDATE Savings
SET BalanceDue = BalanceDue - 100
WHERE AccountIO = 17
UPDATE Checking
SET BalanceDua = BalanceDue + 100
WHERE AccountID = 17

,
,
Transaction. , . , , . . 11-16 ,
(' , ).
, ?
. ,
, .
, . .
. 11-17.

11

445

"^W"

. 11-16.

|
-J^erct^,

>

1^__^

. 11-17.

, .,
, , .
. , ,
.
. ,
. ,
, , ,
. , , (distributed transaction),
+ . , , +.
Philip A. Bernstein Eric Newcomer Principles of Transaction Processing*,
Morgan Kaufmann, 1997.



.

.

446

HI

: DataSet ADO.NET

, , .
,
,
.
,
.

(two-phase commit). , .
. . .
, . ,
, , .
. , , . , , ,
, (, ). ?
.
. , ,
- , ,
.
,
. , , , . , , - ,

, .
, .

.NET Framework
Microsoft
Windows Windows NT 4.
Windows Component
Services.

11

447

, , Component Services,
. , , Component Services .
. . 11-18
Component Services.

. 11-18.
Component Services


,
Component Services.
(, SQL Server Oracle) ,
(Access. DBASE . .) . ,
Component Services.
tic . , Microsoft Message Queuing .


.NET- . -, ,
. Component Services
. , -
, ? -, ,

448

III : DataSet ADO.NET

SystemEnterpriseServices ServicedComponent.
, .
Component Services
Sn.exe RegSvcs.exe. Bin Framework SDK
(strong name). , Framework,
Component Services.
, .
:
Visual Basic .NET
Imports System.Reflection
' +
Ossernbly: ApplicationName("MyServiceComponent")>
'
Ossembly: AssemblyKeyFileAttribute("MyServiceCornponent.snk"}>

Visual C# .NET
using System.Reflection;
// +
[assembly: ApplicationNaiefMyServiceComponent")]
//
[assembly: AssemblyKeyFileAttribute("MyServiceComponent.snk")]


MSDN.
TransactionOption
, Component Services,
, , -
Component Services .
TransactionOption , . . ,
. .
Visual Basic .NET
<Transaction(TransactionOption.Required)>
Public Class clsDistributedTransaction
Inherits ServicedComponent

11

449

Visual C# .NET
[Transact ion(TransactionOpt ion. Required)]
public class TxOemoSvr : ServicedComponent

TmnsactionOption
(. 11-2).
11-2. TransactionOption

Disabled

NotSupported

Supported

Required

RequiresNew

.
,

, ,

, .
,

ADO.NET-
Component Services ,
, ADO.NET- Component Services,
. ADO.NET-.
Component Services.
. Component Services
.

, , , , .
, , ,
. SetAbort
ContextUtil, .
SetComplete.ContextUtil.
Visual Basic .NET
Public Sub MyTransactionalMethod()

Try
'Connect.
'Run queries,
'Disconnect.
If blnSuccess Then

450

ill : DataSet ADO.NET


ContextUtil.SetComplete()
Else

ContextUtil.SetAbortO
End If
Catch ex As Exception
ContextUtil. SetAbortO
Throw New Exception("Unexpected exception: " & ex.Message)
End Try
End Sub

Visual C# .NET
public void MyTransactionalMethodO
try
\
//Connect.
//Run queries.
//Disconnect.
if (blnSuccess)
ContextUtil.SetComplete();
else
ContextUtil. SetAbortO;
>
catch (Exception ex)
{.SetAbortO;
throw
ContextUtil new Exception("Unexpected exception: " + ex.Message);
}

ContextUtil +. MSDN.
: SetComplete , Component Services . .

SetAbort,
, .

, : .
, .

, Component Services (, Microsoft Transaction Server),
SetComplete SetAbort. , )
.

11

451

, , , : , . , AutoComplete. AutoComplete , Component


Services , , .
; AutoComplete
, .
AutoComplete , :
Visual Basic .NET
<AutoComplete()>
Public Sub MyTransactionalMethod()

Visual C# .NET
[AutoCompleteO]
public void MyTransactionalMethod()
(

, , . : , ,
,

DistributedTransaction
-
( Visual Basic .NET Visual *.NET), . ,
Connection ADO.NET.

. , , , . (. 11-19) .
, ,
, .

452

III

: DataSet ADO.NET

* Distributed Transaction Example

Checking Balance:
Savings Salarce:
Transfer

:. Wi
$500.00

" To Checking
<"* Savings
Cause Fakirs

. 11-19.

DistributedTransaction


Component Services
, - -
Component Services. MSDN
Component Services. ,
Component Servies Framework SDK , .


ADO.NET
CommandBuilder Data Adapter
Configuration Wizard
. , , ,
, .
, ADO.NET, . , ADO.NET.

,
. Data Adapter Configuration Wizard CommandBuilder
,
? ,
, .
. , ,

. Oracle Access, SQL Server MSDE,
, .

11

453

, , , Advanced Options .
CommandBuilder ,
, .
. . , . DataSet,
.
, .
?
. DataSet DataReiation, DataTable Orders Order Details. ADO.NET
.
,
. ,
, .
ADO.NET , . DataSet
ADO.NET - . DataTable, DataAdapter , .
DataSet,
. DataTableSelect,
. .
. Recordset ADO Resync, , . ADO.NET?
. Resync ADO.NET . , DataSet
DataSet
Merge. .

12
XML-

15 ADO.NET XML, .
: XML, . , , .
, XML XSLT XPath, . , XML, XSLT XParh,
.
XML, , , , .
XML- ADO.NET,
XML- Microsoft SQL Server 2000. , , Microsoft SQL Server 2000
XML ( *, 2002). , XML- SQL Server 2000 ADO.NET.
, .

XML

XML
. , XML , ,

12

XML-

455

XML-
. XML- - DataSet ADO.NET Recordset
ADO. .
Microsoft Visual Basic Microsoft Active Server Pages (ASP) XML,
, . ? . XML- Recordset ADO .
ADO 2.1 , Recordset
XML- XML- Recordset.
, XML-, ADO, , . XML-, ADO, ..
, ADO XML-. Recordset Open ,
XML- (undocumented), ADO.
ADO.NET XML ,
. XML- DataSet
ADO.NET . SQL Server 2000
XML- XML- DataSet
ADO.NET. , DataSet
XML-, .
.

XML-
XML-
DataSet,

DataSet XML-
DataSet , XML-, XML- DataSet.
GetXml
XML-, GetXml,
DataSet . . .
. 12-1 DataSet .
, DataSet:
Visual Basic .NET
Dim ds As New DataSetO

FillMyDataSet(ds)
Console.WrlteLine(ds.GetXml)

456

III

: DataSet ADO. NET

Public Sub FillMyDataSet(ByVal ds As DataSet)


Dim strConn, strSQL As String
strConn = "Provider=SQLOLEOB;Data Source=(local)\NetSDK; " & _
"Initial Catalog=Northwind;Trusted_Connection=Yes; "
strSQL = "SELECT OrderlD, CustomerlD, OrderDate FROM Orders " & _
"WHERE CustomerlD = 'GROSR'"
Dim daOrders, daDetails As OleDbDataAdapter
daOrders = New OleDbDataAdapterfstrSQL, strConn)
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " & _
"FROM [Order Details] WHERE OrderlD IN (SELECT " & _
"OrderlD FROM Orders WHERE CustomerlD = 'GROSR')"
daDetails = New OleDbDataAdapterfstrSQL, strConn)
daOrders. Fill(ds, "Orders")
daDetails. Fill(ds, "Order Details")
End Sub

Visual C# .NET
DataSet ds = new DataSetQ;
FlllMyDataSet(ds);
Console. WriteLine(ds.GetXmlO);
static void FillMyDataSet(DataSet ds)
i
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK; " +
"Initial Catalog=Northwind;Trusted_Connection=Yes; ";
StrSQL = "SELECT OrderlO, CustomerlD, OrderDate FROM Orders " +
"WHERE CustomerlD = ' GROSR'";
OleDbDataAdapter daOrders, daDetails;
daOrders = new QleDbDataAdapter(strSQL, strConn);
strSQL = "SELECT OrderlD, ProductID, Quantity, UnitPrice " +
"FROM [Order Details] WHERE OrderlD IN (SELECT " +
"OrderlD FROM Orders WHERE CustomerlD = 'GROSR')";
daDetails = new 01eDbDataAdapter(strSQL, strConn);
daOrders. Fill(ds, "Orders");
daDetails. Fill(ds, "Order Details");

WriteXml ReadXml
, GetXml . DataSet.WriteXml .
DataSet , Stream, TextWriter
XmlWriter.
, WriteXml XmlWriteMode,
.
,
DataSet DataSet diffgram.

12 XML-

457

XML- Microsoft Internet


Explorer, , Internet Explorer
. WriteXml DataSet ( )
Internet Explorer (. 12-2), FittMyDataSet,
. , Microsoft
Internet Controls Add
Reference.

. 12-1. DataSet
XML- GetXml
3 ;iKiima.>:HL - Inien

n.9iri4-"Di^erlO'' cvpp"icf:lnt" minOcc:


- i := UnitPric" trpe-nHt:dimar

. 12-2.

'6-3958

DataSet Internet Explorer

458

IN : DataSet ADO.NET

Visual Basic .NET


Dim ds As New DataSet(}
FlllMyDataSet(ds)
Dim strPathToXml As String = "C:\HyData.XHL"
ds.WriteXml(strPathToXml, XmlWriteMode.WriteSchema)
ShowXmllnlE(strPathToXml)
Public Sub ShowXmlInIE(ByVal strPathToXml As String)
Dim ie As New SHDocVw.InternetExplorerQ
ie.Navigate(strPathToXrol)
ie.Visible = True
End Sub
Visual C# .NET
DataSet ds = new DataSetQ;
FillMyOataSet(ds);
string strPathToXml = "C:\\NyData.XML";
ds.WriteXml(strPathToXml, XmlWriteMode.WriteSchema);
ShowXmllnlE(strPathToXml);
static void ShowXmlInIE(string strPathToXml)

SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorerClass();


object objEmpty = Type.Missing;
ie.Navigate(strPathToXml, ref objEmpty, ref objEmpty,
ref objEmpty, ref objEmpty);
ie.Visible = true;

'
Navigate InternetExplorer . * . Type Missing.
DataSet ReadXml,
DataSet . , WriteXml
, Stream. TextReader XmlReader. , ReadXml XmlReadMode, XML.

WriteXmlSchema, ReadXmlSchema InferXmlSchema


DataSet ReadXmlSchema WriteXmlScbema .
, Stream,
TextReader XmlReader.

12 XML-

459

ReadXmlSchema
XML- XML Schema Definition (XSD) XML Data Reduced
(XDR), XML-.
DataSet InferXmlSchema. ReadXmlSchema. , , XML- ,


, , . XML-, ReadXml.
, ReadXml
DataSe, XML-, DataSet .
DataSet, , .
XML- DataSet, ReadXml
. ,
.
. .
. ADO.NET ,
, - . ? , XML (XML ):
<MailingLabel>
<First_Name>Randal</First_Name>
<Last_Naflie>Stephens</Last_Name>
<Address>123 Main St.</Address>
<City>Sometown</City>
<Region>MA</Region>
<PostalCode>01234</PostalCode>
</MailingLabel>

,
. . :
ADO.NET XML-,
, ADO.NET , . ,
, .
XML- . .

460

IN : DataSet ADO.NET

ADO.NET, XML-
XML- . ,
. XML- . 12-3 12-4-
, .
DataSet,
, ADO.NET , DataSet. , DataSet .

- : Orders
s rd erlD > 1 02 6 < /Ordi I >
i; sto m e rl D > G / us ! >
rGrdt'Dai.e s-1 996-07- SOTOOiOOiOO. Q DDDDnD-D7:00</Onjir!J4te

< P if UCti L Z< rt>roducUD >


Quantity 1 0</<3u4ri6t; f

< FYOductID > 7Z </P rodurtIO >


sQu*IH-tr>4-c/Quantrty
= U nits I ;CO> 2 7.8-s /Urn IF >

. 12-3. XML-

<M)'Ns:LlneItem MvfJsiOrdsrlfJ-'lClZfia' H/t:s ProCgi-ID-'ZS" -,--

1996-07-3DTOO: 00:00.ooaaoaa-D7;oo
MfHjiUriilprice-'^.B" /.
- 1 997-1 -:00:00.0000000-:00'

/Ns Line Item Mrhs Ci i;e.lD-"l 0765" Mi^.PioduMID-'^S" M;f

. 12-4. XML- ,
, ADO.NET XML DataSet,
, DataSet. . 12-3 12-4
DataSet. .

: . ADO.NET
. DataSetName
DataSet. DataTable TableName ColumnName

12

XML-

461

DataColumn ,
,
: ?

. . 12-3 ,
. 12-4 .
ColumnMappings
DataColumn. ColumnMappings Element.
, , Attribute. , XML, ColumnMappings Hidden.


. 12-3 ,
. 12-4 , . Nested DataRelation. False,
. 12- 3. Nested True, ADO.NET (. 12-4),


DataSet, DataTable DataColumn Namespace Prefix,
. . 12-4 Namespace
http://unvw.microsqft.com/MyNamespace, Prefix MyNs.

XML-
, ADO 2.1
Recordset XML-, , Recordset
XML-. XML- ,
Recordset ADO.
, .
6 10 , DataRow ADO.NET
, XML-,
. XML- DataSet,
ADO.NET - ,
, .
, DataSet ,
WriteXml, XML- , . WriteXml XML- .

462

III

: DataSet ADO. NET

XML- diffgram
, WriteXml
XmlWriteMode. DiffGram,
WriteXml, ADO. NET
DataSet XML- diffgram. . 1 2-5 . DataSet DataAdapter.

eC-r,ip,-.T.-4.!mf vNodlfled N
Cus(ornri>
Cus'.imeri diH-qi :id=' Ciirtom*rm4h ni^d*"
<C.ustomerID>*NEWl<.'i?uP-oirlD>
<CornbfliliNarrie>Nn4 *

Custom er>Nl*.'Cu5fornei-lC>
<Cnmp.iT-K.'j'.i.1' -Ana Trujillo Emparpdada

, .

- ..'

. 12-5. DataSet,
XML- diffgram
XML-, . 12-5.
DataSet ( ,
) XML- diffgram.
, , ,
DataSet, XML-
diffgram. ShowXmllnlE,
Microsoft Internet Controls.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;TrtJSted_Connection=Yes;"
strSQL = "SELECT TOP 3 CustomerlD, CompanName FROM CustomersDim da As New 01eDbDataAdapter(strSQL, strConn}
Dim ds As New DataSet(}
da.Ftll(ds, "Customers")
Dim tbl As DataTable = ds.TablesC'Customers")
'

12 XML-

463

'
tbl.Rows(1)("CompanyName") = "Modified Company Name"
'
tbl.Rows(2).Delete()
'
tbl.Rows.Add(New Object{) {"ANEW1", "New Company Name"})
' XML- diffgram
' Internet Explorer
Dim strPathToXml As String = "C:\MyData,XML"
ds.WriteXml(strPathToXml, XmlWriteMode.DiffGram)
ShowXmllnlE(strPathToXml)

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT TOP 3 CustomerlD, CompanyName FROM Customers";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn};
DataSet ds = new OataSetO;
da.Fill(ds, "Customers");
DataTable tbl = ds.Tables["Customers"];
//
//
tbl.Rows[1]["ConipanyName"] = "Modified Company Name";
//
tbl.Rows[2].Delete();
//
tbl.Rows.Add(new object[] {"ANEW1", "New Company Name"});
// XML- diffgram
// Internet Explorer
string StrPathToXml = "C:\\MyData.XML";
ds.WriteXml(strPathToXml, XmlWriteMode.DiffGram);
ShowXmllnlE(strPathToXml);

DataSet + XmlDocument = XmlDataDocument


XML- DataSet,
.
DataSet DataSet,
, ADO.NET XML-, .
DataSet XML, XmlDocument. Load,

464

III

: DataSet ADO.NET

XML-,
DataSetWriteXml XML-, XmlDocumentLoad . , , - .
,
. !

XmlDataDocument
XmlDataDocument.
, XmlDataDocument XmlDocument, DataSet. XmlDataDocument XmlDocument, XmlDataDocument
, XmlDocument.
XmlDataDocument . DataSet XmlDocument . XmlDataDocument DataSet. DataSet
XmlDataDocument. ,
.

DataSet XML-
XML
XML-, XmlDataDocument
DataSet XML-.
, XmlDataDocument, DataSet, DataSet XPath.
XmlDataDocument,
DataSet . XPath XmlDataDocument .
FillMayDataSet,
SystemXml
Visual Basic .NET
'
Imports System.Xml
Dim ds As New DataSetO
FillMyDataSet(ds)
Dim xmlDataDoc As New XmlDataDocument(ds)
Dim nodOrder, nodDetail As XmlNode
Dim strXPathQuery As String
strXPathQuery = VNewDataSet/Orders[OrderID=10268]"
nodQrder = xmlDataDoc.SelectSingleNode(strXPathQuery)
Console.WriteLine("OrderID = " & nodOrder.ChildNodes(O).Inner-Text)
Console.WriteLine("CustomerID = " & nodOrder.ChildNodes(O).Inner-Text)
Console.WriteLine("OrderDate = " & nodOrder.ChildNodes(O).InnerText)
Console.WriteLine("Line Items:")

12 XML-

465

strXPathQuery = "/NewDataSet/Order_x0020_Details[OrderID=10268]"
For Each nodDetail In xmlDataDoc. SelectNodes(strXPathQuery)
Console. WriteLine(vbTab & "ProductID = " &
nodDetail. ChildNodes(l).InnerText)
Console. WriteLine(vbTab & "Quantity = " &
nod Detail. ChildNodes( 2). InnerText)
Console. WrlteLine(vbTab & "UnitPrice = " & _
nodDetail. ChildNodes(3). InnerText)
Console. WriteLine()
Next nodDetail
Visual C# .NET
//
using System. Xml;
DataSet ds = new DataSetO;
FillMyOataSet(ds);
Xml Data Document xmlDataDoc = new XmlDataDocumentCds);
XmlNode nodOrder;
string strXPathQuery;
strXPathQuery = '7NewDataSet/Orders[OrderID=10268]1';
nodOrder = xmlDataDoc. SelectSingleNode(strXPathQuery);
Console. WriteLineC'OrderlD = " + nodOrder. ChildNodes[0]. InnerText);
Console. WriteLine("CiistomerID = " +
nodOrder. ChildNodes[1]. InnerText);
Console. Writel_ine("OrderDate = " + nodOrder. ChildNodes[2]. InnerText);
Console. Writel_ine(" Line Items;");
strXPathQuery = "/NewDataSet/Order_x0020_Details[OrderID=10268]";
foreach (XmlNode nodDetail in xmlDataDoc. SelectNodes(strXPathQuery))
{
Console. WriteLine( "YtProductID = " +
nod Detail. ChildNodes[1]. InnerText);
Console. WriteLineC "\tQuantity = " +
nodDetail. ChildNodes[2]. InnerText);
Console. WriteLine("\tUnitPrice = " +
nodDetail . ChildNodes[3] . InnerText) ;
Console. WriteLineO;

XML-
, , XML-
, XML- .
XmlDataDocument , XML- DataSet. XML-, XmlDataDocument DataSet. ,
DataSet , .
. XPath -

466

til : DataSet ADO.NET

(CustomerID), .
DataRou\ ,
, CustomerlD.
DataAdapter
.
XML-, EnforceConstraints DataSet False. ADO.NET . XmlDataDocument DataSet, EnforceConstraints
True, .
Visual Basic .NET
'
Imports System.Xml
Dim ds As New DataSetO
FillMyDataSet{ds)
Dim tblOrders As OataTable = ds.Tablesf'Orders")
tblQrders.PrimaryKey = New DataColumnO
{tblOrders.Columns("OrderID")}
Dim xmlDataDoc As New XmlDataDocument(ds)
Dim nodOrder, nodDetail As XmlNode
Dim strXPathQuery As String = "/NewDataSet/Orders[OrderID=10268]"
nodOrder = xmlDataDoc.SelectSingleNode(strXPathQuery)
ds.EnforceConstraints = False
nodOrder. ChildNodesO). InnerText = "ALFKI"
ds.EnforceConstraints = True
Dim row As DataRow = tblOrders.Rows,Find(10268)
Console.WriteLlne("OrderID = " & rowC'OrderlD"))
Console.WriteLine(vbTab & "Current CustomerlD = " i
rowC'CustomerlD"))
Console.WriteLineCvbTab & "Original CustomerlD = " & _
rowC'CustomerlD", DataRowVersion.Original))

Visual C# .NET
//
using System.Xml;
DataSet ds = new DataSetO;
FillMyDataSet(ds);
OataTable tblOrders = ds.Tables["Orders"J;
tblOrders.PrimaryKey = new DataColumn[]
{tblOrders.Columns["OrderID"]};
XmlDataDocument xmlDataDoc = new XmlDataDocument(ds);
XmlNode nodOrder, nodDetail;
string strXPathQuery = "/NewOataSet/Orders[OrderID=10268]";
nodOrder = xmlDataDoc.SelectSingleNode(strXPathQuery);
ds.EnforceConstraints = false;

12

XML-

467

nodOrder,ChildNodes[1].InnerText = "ALFKI";
ds.EnforceConstraints = true;
DataRow row = tblOrders.Rows.Find{10268);

Console.WriteLineC'OrderlD = " + row["Order!D"]);


Console.WriteLine("\tCurrent CustomerlD = " + row["CustomerID"]);
Console.WriteLineC"\tOriginal CustomerlD = " +
row["CustomerlD", DataRowVersion.0riginal]);
, DataSet. ; DataAdapter.

XML- SQL Server 2000



XML-. , SQL Server
2000 , XML.
DataSet ADO.NET
XmlDataDocument X ML- ,
, XML.

SELECT...FOR XML
SQL Server 2000 SELECT...FOR XML,
XML-.
, , ,
DataSet XmlDocument ADO.NET.
SELECT...FOR XML SQL Server Query Analyzer
SQL Server Query Analyzer. ,
CustomerlD CompanyName Customers.
SELECT TOP 2 CustoierlD, CompanyName FROM Customers
:
" FOR XML AUTO, ELEMENTS"

FOR XML SQL Server XML-; AUTO , ,


: ELEMENTS
. SQL Server , .
Query Results In Text . . 12-6 ,
, .
, XML- SQL Server Query Analyzer - . , ADO.NET
.

468

III : DataSet ADO.NET

SELECT X Customer ID
SSL AUTO, EI.EHSMTS

tCus toner ID>lKTll-:/C4etoerT:p>


<ConipanyKame>Ana T r u ' i l l o Irapdado5 v heJaao=</CompanyHe

; <i.

Query tat*

. 12-6. FOR XML SQL Server Query Analyzer


OleDbCommand
FOR XML, SqlCommand.
SQL Server Client .NET Data Provider ExecuteXmlReader, XmlReader,
.
DataSet
ADO.NET - DataSet. DataSetJZeadXml XmlReader DataSet,
:
Visual Basic .NET
'
Imports System.Data.SqlClient
Imports System.Xml
Dim strConn, strSOL As String
strConn = "Data Source=(local)\NetSDK; " & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT TOP 2 CustonterlD, CompanyName FROM Customers " &
"FOR XML AUTO, ELEMENTS"
Dim en As New SqlConnection(strConn)
cn.0pen()
Dim cmd As New SqlCommand(strSQL, en)
Dim rdr As XmlReader = cmd.ExecuteXmlReader
Dim ds As New DataSet()
ds.ReadXml{rdr, XmlReadHode.Fragment)
rdr.Closet)
en.Close()
Dim strPathToXml As String = "C:\MyData.XML"
ds.WriteXml(strPathToXml)
ShowXmllnlE(strPathToXml)

12 XML-

469

Visual C# .NET
//
using System.Data.SqlClient;
using System. Xinl;
string strConn,

strSQL;

strConn = "Data Source=(local)\\NetSDK;" +


"Initial Catalog=Northwind;Trusted_Connection=Yes;";
StrSQL = "SELECT TOP 2 CustomerlD, CompanyName FROM Customers " +
"FOR XML AUTO, ELEMENTS";
SqlConnection on = new SqlConnection(strConn);
cn.OpenO;
SqlCommand cmd = new SqlCommand(strSQL, en);
XmlReader rdr = cmd.ExecuteXmlReader();
DataSet ds = new DataSetO;
ds.ReadXml(rar, XmlReadMode.Fragment);
rdr. CloseC);
cn.CloseO;
string strPathToXml = "C:\\HyData.XHL";
ds.WriteXml(strPathToXml);
ShowXmlInIE{strPatnToXtnl);

, , , DataSetReadXml
Fragment. XML, (well-formed) XML. . 12-6, , .
XML-
. XML-. ,
ReadXml , XmlReader ~
X ML-.
XmlDocument
XML-, XmlDocument .
XmlDocument Load XmlReader.
XmlDocument , .
:
Visual Basic .NET
'
Imports System.Data.SqlClient
Imports System.Xml
Dim xmlDoc As New XmlDocument()
Dim nodRoot As XmlElement
nodRoot = xmlDoc.AppendChild(xmlDoc.CreateElement("ROOT"))
Dim strConn, strSQL As String
strConn = "Data Source={local)\NetSDK;" & _

470

III

: DataSet ADO.NET

"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT TOP 2 CustomerlD, CompanyName FROM Customers " & _
"FOR XML AUTO, ELEMENTS"
Dim en As New SqlConnection(strConn)
en.()
Dim cmd As New SqlCommand(strSQL, en)
Dim rdr As XrnlReader = cmd.ExecuteXmlReader
Do Until rdr,EOF
nodRoot. AppendChild(xmlDoc. ReadNode( rdr
Loop
rdr.Closet)
cn.CloseO
Dim strPathToXrnl As String = "C:\MyData.XML"
xmlDoc. Save{strPathToXml)
ShowXmllnlE(strPathToXml)

Visual C# .NET
//
using System.Data.SqlClient;
using System.Xml;
XmlDocument xmlDoc = new XmlDocumentQ;
XmlElement nodRoot;
nodRoot = xmlDoc.AppendChild(xmlDoc.CreateElement("ROOT"));
string strConn, strSQL;
strConn = "Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT TOP 2 CustomerlD, CompanyName FROM Customers " +
"FOR XML AUTO, ELEMENTS";
SqlConnection en = new SqlConnection(strConn);
cn.0pen();
SqlCommand cmd = new SqlCommand(strSQL, en);
XmlReader rdr = cmd. ExecuteXmlReaderO;
rdr.Close();
cn.CloseO;
string strPathToXml = "C:\\HyData.XML";
xmlDoc.Save(strPatnToXml);
ShowXmllnlE(strPatnToXnil);

SQL XML .NET Data Provider


XML- SQL Server SQL XML .NET Data Provider.
.NET Framework, Web-
MSDN SQL Server.
, MicrosoftDataSqtXml.
SQL XML .NET Data Provider .NET- .- SQL Server.

12 XML-

471

, XML- SQL Server . SQL XML .NET Data Provider " .NET (
-, ,
*): SqlXmlCommand, SqlXmlAdapter SqlXmlPammeter,
XML- SQL Sewer
SQL XML .NET Data Provider, .

XmlDocument
SqlXmlCommand
XML- SQL Server XmlDocument ,
SqlXmlCommand. SqlXmlCommand , SQL Server. SQL XML
.NET Data Provider SQL Server , OLE DB. ,
, OleDbConnection.
OleDbConnection, CommandText. , ExecuteXmlReader, , XmlReader.
XML-,
XML-, .
SqlXmlCommand RootTag, XML-.
, XmlDocument
, XmlDocumentjioad:
Visual Basic .NET
'
Imports Microsoft.Data.SqlXml
Imports System.Xml
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEOB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Tru5ted_Connecl:ion=Yes;"
strSQL = "SELECT TOP 2 CustomerlD, CompanyName FROM Customers " &
"FOR XML AUTO, ELEMENTS"
Dim cmd As New SqlXmlCornmand(strConn)
cmd.CommandText = strSQL
cmd.RootTag = "ROOT"
Dim xmlDoc As New XmlDocumentO
Dim rdr As XmlReader = cmd.ExecuteXmlReader
xmlDoc.Load(rdr)
rdr.Close()
Dim strPathToXml As String = "C:\MyData.XML"
xmlDoc.Save(st rPathToXml}
ShowXmllnlE(strPathToXml)

472

til

: DataSet ADO.NET

Visual C# .NET
//
using Microsoft.Data.SqlXml;
using System.Xml;
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
StrSQL = "SELECT TOP 2 CustomerlD, CompanyName FROM Customers " +
"FOR XML AUTO, ELEMENTS";
SqlXmlCoinmand cmd = new SqlXmlCommand{strConn);
cmd.CommandText = strSQL;
cmd.RootTag = "ROOT";
XmlDocument xmlDoc = new XmlDocumentO;
XmlReader rdr = cmd. ExecuteXmlReaderO;
xmlDoc.Load(rdr);
rdr.Close();
string strPathToXml = "C:\\MyData.XML";
xmlDoc.Save(strPathToXml);
ShowXmllnlE(strPathToXinl);

DataSet
SqIXmlAdapter
XmlReader DataSet,
SQL XML .NET Data Provider SqIXmlAdapter.
FOR XML DataSet, , OleDbDataAdapter
SQL-.
SqlXmlCommand
SqlXmlCommand, SqlXmlCommand,
DataSet , SqlXm-IAdapterfillVisual Basic .NET
'
Imports Microsoft.Data,SqlXml
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
StrSQL = "SELECT TOP 2 CustomerlD, CompanyName FROM Customers
"FOR XML AUTO, ELEMENTS"
Dim cmd As New SqlXmlConnnand(strConn)
cmd.CommandText = strSQL
cmd.RootTag = "ROOT"
Dim da As New SqlXmlAdapter(cmd)
Dim ds As New DataSetQ
da.Fill(ds)

12 XML-

473

Dim strPathToXml As String = "C;\MyData.XML"


ds.WriteXmlCstrPathToXml)
ShowXmllnlE(strPathToXml)

Visual C# .NET
//
using MicrosoftrData.SqlXml;
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local}\\NetSOK;" +
"Initial Catalog=Northwind;TrustecLConnection=Yes;";
strSQL = "SELECT TOP 2 CustomerlD, CotnpanyName FROM Customers " +
"FOR XML AUTO, ELEMENTS";
SqlXmlCommand cmd = new SqlXmlCommand(strConn);
cmd.CommandText = strSOL;
cmd.RootTag = "ROOT";
Dim da As New SqlXmlAdapter(cmd)
Dim ds As New DataSetO
da.Fill(ds)
string strPathToXml = "C:\\MyData.XML";
ds.WriteXml(strPathToXml);
ShowXmlInIE{strPathToXml);


SQL XML
.NET Data Provider XML- . , XML-, . , (template query; ), SQL XML .NET Data Provider XML- .
SELECT...FOR XML,

:
<?xml version="1.0" encoding="utf-8" ?>
<ROOT xmlns:sql='urn:scnetnas-nticrosoft-com:xiril-sqr;'
<sql:query>
SELECT OrderlD, CustomerlD, OrderDate FROM Orders
WHERE CustomerlD * 'GROSFT
FOR XML AUTO, ELEMENTS
</sql:query>
<sql:query>
SELECT OrderlD, ProductID, Quantity, UnitPrice
FROM [Order Details] WHERE OrderlD IN
(SELECT OrderlD FROM Orders WHERE CustomerlD = 'GROSR')
FOR XML AUTO, ELEMENTS
</sql:query>
</ROOT>

III : DataSet ADO.NET

474

3 CrWyOata.XMl - Microsoft Interne =ile

Edit

View

Fa.vorifes

loob

-; Customers
<CustaroerIP>GRaSR</CustomerID>
< Company ^arr
< Orders >
<Order!D>1026i</OrderID>
/Orders >
<Order$>
<OrderID>107B5</OrderID>
<Customef-ID>GRQSR-</CustolTierIDs
< Order Date? 1997-1 2- 18TOO:OQ;00^/OrderDate
e /Orders >

My Computer

, 12-7.

XML-. SQL XML .NET Data Provider


, sql, ,
-. XML- .
. 12-7 XML-,
SQL XML .NET Data Provider. , .
SqIXmtCommand
SqlXmlCommand, SqlXmlCommand, CommandType
SqlXmlCommandType.
, CommandType TemplateFile. ,
CommandType Template.
XML- DataSet, .
DataSet:
Visual Basic .NET
'
Imports Microsoft.Data.SqlXml
Dim strPathToResults As String = "C:\MyResults.XHL"
Dim strPathToQuery As String = "C:\HyTemplateQuery.XHL"
Dim strConn As String = "Provider=SQLOLEDB;" &
"Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;" & _
"Trusted_Connectlon=Yes;"

12

XML-

475

Dim cmd As New SqlXmlCommand(strConn)


cmd.CommandText = strPathToQuery
cmd.CommandType = SqlXmlComniandType.TeinplateFile
Dim ds As New DataSetO
Dim da As New SqlXmlAdapter(cmd)

da.Fill(ds)
ds.WriteXml(strPathToResults)
ShowXmllnlE(strPathToResults)

Visual C# .NET
//
using Microsoft.Data.SqlXml;
string strPathToResults = "C:\\KyResults.XML";
string strPathToQuery = "C:\\MyTemplateQuery.XML";
string strConn = "Provider=SQLOLEDB; Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
SqlXmlCommand cmd = new SqlXmlCommand(strConn);
cmd.CommandText = strPathToQuery;
cmd.CommandType = SqlXmlCommandType.TemplateFile;
DataSet ds = new DataSetO;
SqlXmlAdapter da = new SqlXmlAdapter(cmd);
da.Fill(ds);
ds.WriteXml(strPathToResulta);
ShowXmlInIE{StrPathToResults);

. (
), CustomerlD, :
<?xml version="1.Q" encoding="utf-8" ?>
<ROOT xmlns:sql='urn;schemas-microsoft-com:xml-sqr>
<sql:header>
<sql:pararo narae="CustomerID"/>
</sql:header>
<sql:query>
SELECT OrderlD, CustomerlD, OrderDate FROM Orders
WHERE CustomerlD = >CustomerID
FOR XML AUTO, ELEMENTS
</sql:query>
<sql:query>
SELECT OrderlD, ProductID, Quantity, UnitPrice
FROM [Order Details] WHERE OrderlD IN
(SELECT OrderlD FROM Orders WHERE CustomerlD = @CustomerID)
FOR XML AUTO, ELEMENTS
</sql;query>
</ROOT>

476

III

: DataSet ADO.NET

, SqlXmlParameter. New
. SqlCommand.CreateParameter. SqlXmlParameter,
Name Value :
Visual Basic .NET
Dim cmd As SqlXrolCommand
Dim param As SqlXmlParameter = cmd.CreateParafneterO
param.Name = "@CustomerID"
param.Value = "GROSR"

Visual C# .NET
SqlXmlCommand cmd;
SqlXmlParameter param = cmd.CreateParameterf);
param.Name = "iPCustomerlD";
param.Value = "GROSR";

XPath
XML- Northwind,
XPath , (CustomerlD) GROSR:
Orders[CustofnerID='GROSfl']

SqlXmlCommandType,
XPath. CommandType SqlXmlCommand XPath,
CommandText XPath , , .
SQL Server , XPath. SQL XML .NET Data Provider XPath, ,
SELECT...FOR XML,
XPath , SQL XML .NET Data Provider .

SQL XML .NET Data Provider XPath,
XML-,
, :
<?xml version 5 5 "1.0" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xsd: artnotation>
<xsd:appinfo>
<sql:relationship name="relOrdersDetails"

12 XML-

477

parent="0rders"
parent-key="OrderID"
child="[0rder Details]"
child-key="Order!D" />
</xsd:appinfo>
</xsd:annotation>
<xsd:element name="0rders">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="OrderID" typ6="xsd:int" />
<xsd:element name="CustomerID" type="xsd:string" />
<xsd:element natne="OrderDate" type="xsd:dateTime"
sql:datatype="datetime" />
<xsd:element name="Order_x0020_Details"
sql:relation="[0rder Details]"
sql:relationship^'relOrdersDetails">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="ProductID" type="xsd:int" />
<xsd:element name="Quantity" type="xsd:int" />
<xsd:element name="UnitPrice" type="xsd:decimal" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd;schema>
, ,
(sql:relationship) SQL XML .NET Data
Provider SQL- (sqldatatype). ,
XML- SQL XML .NET Data Provider. Using Annotations in XSD Schemas SQL
XML3.
, SchemaPatb
SqlXmlCommand.
XPath , , .
XmlDocument.
Visual Basic .NET
'
Imports Microsoft.Data.SqlXml
Imports System.Xml
Dim strPathToResults As String = "C:\MyResults.XML"
Dim strPathToSchema As String = "C:\HySchema.XSD"

478

III

: DataSet ADO.NET

Dim strConn As String = "Provider=SQLOLEDB;" & _


"Data Source=(local}\NetSDK;" & _
"Initial Catalog=Nortnwind;" & _
"Trusted_Connection=Yes;"
Dim cmd As New SqlXmlCommand(strConn)
cmd.SchemaPath = StrPathToSchema
cmd.CommandText = "Qrders[CustomerID= T GROSR']"
cmd.CommandType = SqlXmlCommandType.XPath
Dim rdr As XmlReader = cmd.ExecuteXmlReader()
Dim xmlDoc As New XmlDocument()
xmlDoc.Load(rdr)
rdr.CloseO
xmlDoc.SaveCst rPathToResults)
ShowXmllnlE(strPathToResults)

Visual C# .NET
//
using Microsoft.Data.SqlXml;
using System.Xml;
string strPathToResults = "C:\\MyResults.XHL";
string strPathToSchema = "C:\\MySchema.XSD";
string strConn = "Provider=SQLOLEOB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
SqlXmlCommand cmd = new SqlXmlCommancKstrConn);
cmd.SchemaPath = strPathToSchema;
cmd.CommandText = "Orders[CustomerID='GROSR']";
cmd.CommandType = SqlXmlCommandType.XPath;
XmlReader rdr = cmd.ExecuteXmlReader();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc,Load(rdr);
rdr.CloseO;
xmlDoc.Save(StrPathToResults);
ShowXmlInIE(strPathToResults);

XSLT-
, XML, XML- ,
. XSLT (extensible
Stylesheet Language Transformations) XML-.
, XSLT- XML-
, XML. XSLT- ,
. , XSLT- XML HTML.
SQL XML XSLT-,
XslPatb SqlXmlCommand .
.

12

XML-

.'-79


SQL XML .NET Data Provider ,
SqIXmlAdapter Update', , DataSet. 10, DataAdapter .
SqIXmlAdapter ,
DataAdapter, (. OleDbDataAdapter, SqlDataAdapter
OdbcDataAdapter) , Command
, . Command , DataTable.
Update DataAdapter
DataTable. , DataAdapter
. Command DataRowAcceptCbanges.
SqIXmlAdapter .
XML- diffgram (. 12-5).
DataSet, DataRow
, SqIXmlAdapter DataSet , XML- diffgram.
SQL XML .NET Data Provider , .
XML- diffgram . 12-5, ,
, , INSERT, UPDATE DELETE
. SQL XML
.NET Data Provider .
XML-, SQL XML .NET
Data Provider XPath SQL-? , . XPath SchemaPath
SqlXmlCommand . SqIXmlAdapter , ,
SqlXmlCommand , , XML- diffgram.
SqlXmlCommand, CommandText DiffGram. XML- diffgram, DataSetWriteXml.
SqlXmlCommand ,
...! :
Visual Basic .NET
'
Imports Microsoft,Data.SqlXml
Imports System.Xml
Imports System.10
Dim strConn As String = "Provider=SQLOLEDB;" 4 _

480

111 : DataSet ADO.NET

"Data Source=(local)\NetSDK;" & _


"Initial Catalog=Northwind;" &
"Trusted_Connection=Yes;"
Dim cmd As New SqlXmlComfnand(strConn)
Dim strPathToSchema As String = "C:\MySchema.XSD"
cmd.SchemaPath = strPathToSchema
cmd.CommandText = "Orders[CustomerID='GROSR']"
cmd.CommandType = SqlXmlCommandType.XPath
cmd.RootTag = "ROOT"
Dim da As New SqlXmlAdapter(cmd)
Dim ds As New DataSetO
da.FillCds)
ds.Tables("Orders").Rows(0)("CiJstomerID") = "ALFKI"
ds.Tables("Orders").Rows(1)("CiJStonierrD"} = "ALFKI"
Dim strPathToDiffGram As String = "C:\MyDiffGram.XML"
ds.WriteXml(strPathToDiffGram, XffllWriteMode.DiffGram)
cmd = New SqlXmlCommand(strConn)
cmd.SchemaPath = strPathToSchema
cmd.CommandType = SqlXmlCommandType.DiffGram
cmd.CommandStream = New FileStreamfstrPathToDiffGram,
FileMode.Open, FileAccess.Read)
cmd,ExecuteNonQuery()
'
Dim strSQL As String = "UPDATE Orders SET CustomerlD = 'GROSR' " & _
"WHERE OrderlD = 10268 OR OrderlD = 10785"
cmd = New SqlXmlCommand(strConn)
cmd.CommandText = strSQL
cmd.CommandType = SqlXmlCommandType.Sql
cmd. ExecuteNonQueryO

Visual C# .NET
//
jsing Microsoft.Data.SqlXml;
using System.Xml;
using System.10;
string strConn = "Provider=SQLOLEDB;Oata Source=(locat)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
SqlXmlCommand cmd = new SqlXmlConrniand(strConn);
string strPathToSchema = "C:\\MySchema.XSD";
cmd.SchemaPath = strPathToSchema;
cmd.CommandText = "Qrders[CustomerID='GROSR']";
cmd.CommandType = SqlXmlCommandType.XPath;
cmd.RootTag = "ROOT";
SqlXmlAdapter da = new SqlXmlAdapter(cmd);
DataSet ds = new DataSetO;
da.Fill(ds);

12

XML-

481

ds.Tables["Orders"].Rows[Q]["CustomerID"] = "ALFKI";
ds.Tables["Orders"].Rows[1]["CustomerID"] = "ALFKI";
string strPathToDiffGram = "C:\\MyDiffGrarn.XML";
ds.WriteXml(strPathToDiffGram, XmlWriteMode.DiffGrani);
cmd = new SqlXmlCommand(strCcmn);
cmd.SchemaPath = strPathToSchema;
cmd.CofnmandType = SqlXmlCommandType.DiffGram;
cmd.CommandStreain = new FileStream(strPathToDiffGram, FileHode.Open,
FtleAccess.Read);
cmd. ExecuteNonQueryO;
//
string strSQL = "UPDATE Orders SET CustomerlD = 'GROSR' " +
"WHERE OrderlD = 10266 OR OrderlD = 10785";
cmd = new SqlXmlCommandCstrConn);
cmd.CommandText = strSQL;
cmd.ComnmndType = SqlXmlCommandType.Sql;
cmd. ExecuteNonQueryO;

, .
, SqlXmlCommand XML- diffgram ,
,
, SqlXmlCommand
, ,
SqlXmlCommand .

SQL XML .NET Data Provider.
SqlXmlCommandExecuteNonQuery XML- diffgram, SQL XML .NET Data
Provider SQL Server :
SET XACT_ABORT ON
BEGIN TRAN
DECLARE @eip INT,

@r__ Int,

@e__ int

SET @>eip = 0

UPDATE Orders SET CustomerID=N'ALFKI' WHERE ( OrderID=10268 ) AND


( CustomerID=N'GROSR' ) AND ( OrderDate=N'1996-07-30 00:00:00' ) ;
SELECT _ = @@ERROR, @r__ = @<aROWCOUNT
IF (@e__ != 0 OR @r__ != 1) SET @eip = 1
IF (@r__ > 1) RAISERROR ( N'SQLOLEDB Error Description: Ambiguous update,
unique identifier required Transaction aborted ', 16, 1)
ELSE IF (@r__ < 1) RAISERROR ( N'SQLOLEDB Error Description: Empty update,
no updatable rows found Transaction aborted ', 16, 1)

482

III : DataSet ADO.NET

UPDATE Orders SET CustomerID=N'ALFKI' WHERE ( OrderID=10785 ) AND


( CustomerID=N'GROSR' ) AND ( OrderDate=N'1997-12-18 00:00:00' ) ;
SELECT @e__ = @@ERROR, @r__ = @$ROWCOUNT
IF (@e__ != 0 OR @r__ != 1) SET @eip = 1
IF Or__ > 1) RAISERROR N'SQLOLEDB Error Description: Ambiguous update,
unique identifier required Transaction aborted ', 16, 1)
ELSE IF (@r__ < 1) RAISERROR ( N'SQLOLEDB Error Description: Empty update,
no updatable rows found Transaction aborted ', 16, 1)
IF (0eip != 0) ROLLBACK ELSE COMMIT
SET XACT.ABORT OFF

SQL Server ,
, . UPDATE
, , . , , . , , SQL Server
.
. , , ,
, .
, , .
,
SQL XML .NET Data Adapter
.
,
UPDATE ,
. , ,
.
- .

timestamp.
SqlXmtAdapter.Update, SqlXmlAdapter
DataSetAcceptChanges. SqlXmlAdapter AcceptChanges
DataTable, .

ADO.NET XML
XML ADO.NET ,
XML XML- ADO.NET.

12 XML-

483

, . , , :

Customers. Orders, Order Details Products. , , .
XML-, XSLT XML- HTML-
Internet Explorer (. 12-8).
icfosoft Interne! )1..0Je

Etft

!j.iev*

"'

Fjvoritei
>

Tods

yelp

L *^

Order Histoty The Cracker Br,%


3 Orders

Pro dart
Rossle Sauerkraut

Quantity
10

Tliunnger Rostbiahvum
Cuia Malacca

I
Produrt
". i i

Quantity

Unit Price

Item Total

$4560

Ed 56 00

$123 79

74274

1945

I1S450

Item Total
$18600

Laughing Lumberjack Lager

Product
1

Boston Crab Meat

Fib Mix

. 12-8.

Web-, -

, Internet
Explorer. , ,
. ,
HTML-: Web- . , XML- ADO.NET.
: HTML XSLT , -, . Web- Microsoft FrontPage
XML-, ADO.NET
. , XSLT, , XSLT- XML- HTML-.
:
, XML,
XSLT XML HTML;
, Web- ,

484

III

: DataSet ADO.NET


- , , . XSLT- HTML-,
- XML- Norhtwind.
, DataSetToHTML, Norhtwind .NET
SDK MSDE OLE DB .NET Data Provider.
DataSet.
DataSet, XML-, XSLT-
HTML-, XmlDataDocument,
DataSet.
, SqlXmlToHTML, SQL XML .NET Data
Provider XML- , Northwind, FOR XML. XslPath SqlXmlCommand
XSLT-,

ADO.NET XML:
ADO.NET XML. XML- ADO.NET, XML- . DataSet / XML-.
XmlDataSet DataSet XML-. SQL XML .NET Data Provider XML- SQL Server 2000 XML ,
XML- DataSet.

,
. DataSet, DataTable DataColumn
XML-, WriteXml,
.
XML- , XSLT.
?
. XmlDataDocument
DataSet XML-. EnforceConstraints DataSet
False XmlDataDocument
XML-. CreateProcessinglnstiiiction XmlDataDocument. XmlDataDocument.'
Save XML-.

Visual Basic .NET


Dim ds As New DataSetC)
ds.EnforceConstraints = False
Dim xmlDoc As New XmlDataDocument(ds)
Dim strPI as String = "type='text/xsl' href='HyTransform.XSLTT"
Dim xmlPI as XmlProcessinglnstruction

12 XML-

485

xmlPI = xmlDoc.Create?rocessinglnstruction("xml-stylesheet", strPI)


xmlDoc.InsertBeforefxmlPI, xmlDoc.DocumentElement)
Dim strPathToXmlFile As String = "C:\MyData.XML"
xmlDoc. Save(strPathToXmlFile)

Visual C# .NET
DataSet d's = new DataSetO;
ds.EnforceConstraints = false;
XmlDataDocument xmlDoc = new XmlDataDocument(ds);
string strPI = "type='text/xsl' href='MyTransfortn.XSLT'";
XmlProcessinglnstruction xmlPI;
xmlPI = xmlDoc.CreateProcessingInstruction("xml-stylesheet", strPI);
xmlDoc.InsertBeforeCxmlPI, xmlDoc.DocumentElement);
string strPathToXmlFile = "C:\\HyData.XML";
xmlDoc.Save(StrPathToXmlFile);

. ,
XML-, . ?
. SQL XML .NET Data Provider XML-, ClientSideXml SqlXmlCommand
True, :
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
StrSQL = "EXEC CustOrdersOrders 'ALFKI' FOR XML NESTED"
Dim cmd As New SqlXmlCommand(strConn)
cmd.CommandText = strSQL
cmd.ClientSideXml = True
cmd.RootTag = "ROOT"
Dim xmlDoc As New XmlDocumentO
Dim xmlRdr As XmlReader = cmd.ExecuteXmlReader
xmlDoc.Load(xmlRdr)
xmlRdr.Close
Console.WriteLine(xmlDoc.InnerXral)

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
1
strSQL = "EXEC CustOrdersOrders 'ALFKI FOR XML NESTED";
SqlXmlCommand cmd = new SqlXmlCommand(strConn);
cmd.CommandText = strSQL;
cmd.ClientSideXml = true;

486

III

: DataSet ADO.NET

cmd.RootTag = "ROOT";
XmlDocument xmlDoc = new XmlDocumentf);
XmlReader xmlRdr = cmd. ExecuteXmlReaderO;
xmlDoc,Load(xmlRdr);
xmlRdr.Close();
Console.WriteLine(xmlDoc.InnerXml);

XML
SQL XML .NET Data Provider Comparing Client-Side XML
Formatting to Server-Side XML Formatting SQL XML 3-


ADO.NET

13

Windows-

1, ADO.NET. DataSet DataTable


DataAdapterl . DataRelation DataTable' . ? .
, ,
, .
.
, Windows-, .
, 2
Data Form Wizard. , , . (binary large
object, BLOB) Windows-.



, .
,

13 Windows-

489

, , .
, .
, , DataRow
TextBox .
, , ,
DataSet.
,
,
.
Windows Forms Microsoft .NET Framework . , DataSet
, , . ,
,
, .

DataSet.
ADO.NET, DataSet DataTable, , IList.
ADO.NET,
ADO.NET. .NET Framework SDK.
. . (. 13-1)
, .
, .
Order Details
"roduetlD

UnitPiice Quantity
$45.Hf" 15

iG

. 13-1-

iiemTolal
" $684.00

S12.CC

- , . ,
'7-595

490

IV

ADO.NET

, Microsoft
Visual Basic .NET, Microsoft Visual * .NET.
Northwind.
Microsoft Desktop Engine (MSDE) , c.NET Framework SDK, . 3 .
Northwind.

1. DataAdapter DataSet
Windows-,
Windows- , .
Chapter 13. JrmEditOrders Edit Orders. MaximizeBox False, FormBorderStyle Fixed3D. ,
. ,
, ,
.
, DataAdapter
Northwind. Data
QleDbDataAdapter .
Data Adapter Configuration Wizard ( 5).
Connection Northwind.
. New Connection .
Query Type Use SQL
Statements. SQL Statement SQL-:
SELECT OrderlD, CustomerlD, EmployeelD, OrderDate
FROM Orders WHERE CustomerlD = ?

. -,
, . -, ,
. ; ,
.
,
QleDbDataAdapter OleDbConnection. daOrders cnNortbwind.
Generate DataSet.
DataSet xsdChapterl3 . Solution
Explorer xsdChapterl 3-xsd,
DataSet. dsChapterlB.
OrderlD Orders .
6, DataSet AutoIncrementSeed AutolncrementStep -1.
OrderlD DataSet . Solution Explorer -

13 Windows-

191

DataSet (xsdChapter!3.xsd).
OrderlD. AutoIncrementSeed AutolncremetitStep
-1. .

2.
TextBox
DataAdapter DataSet. lextBox,
.
-, ,
TextBox OrderlD.
Label.
Name IblOrderlD, Text Order ID:. TextBox.
Name txtOrderlD, Text .
- TextBox.
OrderlD DataSet, Properi ies.
(DataBindings). ( ), Data. ; (DataBindings)
. OrderlD Text . (DataBindings), Text ,
. DataSet.
, DataTable.
DataTable Orders. ,
DataColumn. OrderlD (. 13-2).

. 13-2. Text TextBox


DataColumn DataSet
, , Label
TextBox CustomerlD, EmployeelD OrderDate.
Text .

492

IV ADO.NET

TextBox DataSet.
, . 13-3.

frmEdtQrdcri.vh [Btsign]

! 1 J
I Solution 'Chapter 13' (1 protect)
Chapter 13
'+ i] Rrftrsreti
3 uiismbl/Wo.vb
fflffl

*j]

. 13-3.

Label TextBox

, TextBox DataSet
. , :
Visual Basic .NET
txtOrderlD.DataBindings.AddCText", dsChapter13, "Orders.OrderlD")
Visual C# .NET
txtOrderlD.DataBindings.AddCText", dsChapter13, "Orders.OrderlD");
Text OrderlD
Orders DataSet dsChapter!3.
Readonly
TextBox, OrderlD, True, .
, , TextBox , . ,
ForeColor Black.
, TextAlignment
TextBox, OrderlD EmployeelD, Right,
.

13 Windows-

493

3.
DataSet TextBox, ,
. , Label
TextBox. DataSet
.
Visual Basic, , ,
, . .NET
-.
,
. . ,
Load. :
Visual Basic .NET
Dim strCustomerlD As String = "ALFKI"
Visual C# .NET
string strCustomerlD = "ALFKI";
Load :
Visual Basic .NET
daOrders.SelectCommand.Parameters(O).Value = strCustomerlD
daOrders.Fill(dsChapter13.Orders)
Visual C# .NET
daOrders.SelectCommand.Parameters[0].Value = strCustomerlD;
daOrders.Fill(dsChapter13.Orders);
, ,
DataAdapter . , .
, Close.
Click Close , . ,
, Name btnClose Text
Close. ,
Click. :
Visual Basic .NET
Me.CloseO
Visual C# .NET
this.CloseO;

494

IV

ADO.NET

4.
DataSet
. , Count DataTable Orders
DataSet , . - , .
,
.
, ,
(. 13-4).
, .
Jjxl
43

Glided of 6

. 13-4.
DataSet

CurrencyManager. , , . Windows- BindingContext, CurrencyManager,
.
TextBox DataTable
Orders. , Position CurrencyManager. Position ,
.
,
. CurrencyManager
. , Load , ItemChanged PositionCbanged CurrencyManager.
, . , , Click Position CurrencyManager.

13

Windows-

Visual Basic .NET


'
Dim cmOrders As CurrencyManager
Private Sub frmEditOrders_Load. . .
cmdrders = CType(BindingContext(dsChapter13, "Orders"),
CurrencyManager)
AddHandler cmOrders.ItemChanged, AddressOf cmOrders_ItemChanged
AddHandler cmOrders.PositionChanged, AddressOf cmOrders_PositionChanged
DisplayOrdersPosition()
End Sub

Private Sub DisplayOrdersPositlonO


IblOrdersPosition.Text = "Order " & cmOrders.Position + 1 & _
" of " & cmOrders.Count
End Sub
Private Sub cmOrders_ItemChange6(ByVal sender As Object,
ByVal e As ItemChangedEventArgs)
DisplayOrdersPositionO
End Sub
Private Sub cmOrders_PositionChanged(ByVal sender As Object,
ByVal e As System.EventArgs)
DtsplayOrdersPositionO
End Sub
Private Sub btnOrdersMoveFirst_Click...
cmOrders.Position = 0
End Sub
Private Sub btnOrdersMovePrevious_Click...
cmOrders.Position -= 1
End Sub
Private Sub btnOrdersMoveNext_Click...
cmOrders.Position += 1
End Sub
Private Sub btnOrdersMoveLast_Click...
cmOrders.Position = cmOrders.Count - 1
End Sub

Visual C# .NET
//
CurrencyManager cmOrders;
private void frmEdltOrders_Load...

495

496

IV

ADO. NET

i
cmOrders = (CurrencyManager) BindingContext[dsChapterl3, "Orders"];
cmOrders.ItemChanged +=
new ItemChangedEventHandler(cinOrders_ItemChanged);
cmOrders, PosittonChanged += new EventHandler(cmOrders_PositionChanged);
DisplayOrdersPositionf) ;

!
private void DisplayOrdersPositionQ
!
IblOrdersPosition.Text = "Order " + (cmOrders. Position + 1} +
" of " + cmOrders, Count;

I
private void cmOrders_ItemChanged(object sender,
i
DisplayOrdersPositionf ) ;

ItemChangedEventArgs e)

private void cmOrders_PositionChanged(object sender, EventArgs e)


\
DisplayOrdersPositionf ) ;

private void btnQrdersMoveFirst_Click(object sender, System. EventArgs e)


{
cmOrders. Position = 0;
}
private void btnOrdersMovePrevious_Click(object sender,
{
cmOrders. Position-;
}

System. EventArgs e)

private void btnOrdersHoveNext_Click(object sender,


<
cmOrders. Position**;

System. EventArgs e)

private void btnOrdersMoveLast_Click(object sender,


{
cmOrders. Position = cmOrders. Count - 1;

System. EventArgs e)

;-

5. Add Delete
,
DataAdapter, ,
TextBox.

13

Windows-

497

EmployeelD .
?
EmployeelD , . , EmployeelD - .
: EmployeelD?
, ... . Currency Man age r ,
, . AddNeiv ,
RemoveAt . ,
Manager,
. AddNew,
. RemoveAt
.
Visual Basic .NET
Private Sub btnOrdersAdd_CHck. . .
cmOrders.AddNewO
End Sub
Private Sub btnOrdersDelete_Click. . .
If cmOrders. Count > 0 Then
cmOrders.RemoveAt (cmOrders. Position)
Else
MessageBox. Show("No Order to Delete!", "Delete Order",
HessageBoxButtons.OK, MessageBoxIcon. Error)
End If
End Sub
Visual C# .NET
private void btnOrdersAdd_Click(object sender, System. EventArgs e)

<
cmOrders.AddNewO;
SetQrdersEditMode(true);

private void btnOrdersDelete_Click(object sender, System. EventArgs e)


i
if (cmOrders. Count > 0)
cmOrders.HemoveAt (cmOrders. Posit ion);
else
MessageBox. Show( "No Order to Deletel", "Delete Order",
MessageBoxButtons.OK, MessageBoxIcon. Error);

498

IV ADO.NET

6.
, .
, , , . , 5 10, , . DafaSet,
, DataAdapter Update.
DataAdapter Data Adapter Configuration
Wizard, .
. , . Submit Changes
Click DataAdapter.Update,
. Update DataAdapter, .
, , , DataSet ,
DataAdapter,Update-,
Visual Basic .NET
If dsChapter13.HasChanges Then
Try
Dim intOrdersModified As Integer
intOrdersModified = daOrders.Update(dsChapter13.Orders)
Dim strOutput As String
strOutput = "Modified " & intOrdersModified & " order(s)"
MessageBox.Show(strOutput, "Update succeeded!",
MessageBoxButtons,OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message, "Update failed!",
HessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Else
MessageBox.Show("No changes to submit!", "SubmitChanges",
MessageBoxButtons.OK, MessageBoxIcon.Information)

End If

Visual C# .NET
if (dsChapter13.HasChanges()>
i
try

int intOrdersModified;
intOrdersModified = daOrders.Update{dsChapter13. Orders);
string strOutput;
strOutput = "Modified " + intOrdersModified + " order(s)";
MessageBox.ShowfstrOutput, "Update succeeded!",
MessageBoxButtons.OK, MessageBoxIcon.Information);

13

Windows-

499

catch (Exception ex)


1
MessageBox.Show(ex. Message, "Update failed!",
MessageBoxButtons . OK, HessageBoxIcon .Error) ;

else
MessageBox.Stiow("No changes to submit!", "SubmitChanges",
MessageBoxButtons. OK, MessageBoxIcon. Information);

7. Edit, Update Cancel


: . , .
EmployeelD .
Submit Changes.
. ?
, DataSel - .
? CurrencyManager - DataSet. Submit Changes, .
CurrencyManager
DataSet,
CurrencyMariagerEndCurrentEdit. - DataRowBeginEdtt.
DataRow EndEdit.
DataAdapter,Update
CurrencyManager EndCurrentEdit, , .
7 Edit, Cancei Update.
TextBox . , Edit.

TextBox ( , OrderlD). ,
Add, Edit, Delete Submit Changes . Update Cancel
(. 13-5). Update . Cancel .
,
.
. , , . , , , CurrencyManager
DataSet.

IV

500

ADO. NET

CudeilD
Custom tD
EmotojeelD:
Orcfei Dale.

Update

Cance

. 13-5.

SetOrdersEcUtMode, , ,
.
Readonly TextBox, Enabled . Click Add, Edit, Update Cancel.
Visual Basic .NET
Private Sub SetOrdersEditMode(ByVal blnEdit As Boolean)
txtCustomerlO. Readonly = Not blnEdit
txtEmployeelD. Readonly = Not blnEdit
txtOrderDate. Readonly = Not blnEdit
btnOrdersHoveFirst. Enabled = Not blnEdit
btnOrdersMovePrevious. Enabled = Not blnEdit
btnQrdersMoveNext. Enabled = Not blnEdit
btndrdersMoveLast. Enabled = Not blnEdit
btnOrdersCancel. Enabled = blnEdit
btnOrdersUpdate. Enabled = blnEdit
btndrdersEdit. Enabled = Not blnEdit
btnOrdersAdd.Enaoled = Not blnEdit
btnOrdersDelete. Enabled = Not blnEdit
btnSubmitChanges, Enabled = Not blnEdit
End .Sub

Visual C# .NET
private void SetOrdersEditMode(bool blnEdit)
{
txtCustoroerlD. Readonly = ! blnEdit;
txtEmployeelD. Readonly = IblnEdit;
txtOrderDate. Readonly = IblnEdit;
btnOrdersMoveFirst. Enabled = IblnEdit;

13

Windows-

btnOrdersHovePrevious.Enabled = IblnEdit;
btnOrdersMoveNext.Enabled = IblnEdit;
btnOrdersMoveLast.Enabled = IblnEdit;
btnOrdersCancel.Enabled = blnEdit;
btnOrdersUpdate.Enabled = blnEdit;
btnOrdersEdit.Enabled = IblnEdit;
btnOrdersAdd.Enabled = IblnEdit;
btnOrdersDelete.Enabled = IblnEdit;
btnSubmitChanges.Enabled = IblnEdit;

8.

Orders. - , .
. 13-6
. , , Order
Details. ,
.

, 13-6.
:
1. DataAdapter, Order Deiails,
;
2. DataSet ,
DataTable ,
. DataSet DataRelation, ;
3. DataGrid DataSet
,
;
4. , Click Submit Changes,
DataTable.

502

IV ADO.NET


DataAdapter, ,
, Orders CustomerlD. Order Details . , , , Order Details Orders.
. :
SELECT D.OrderlD, D.ProductlD, D.UnitPrice, 0.Quantity
FROM Orders 0 INNER JOIN [Order Details] D
ON O.OrderlD = D.OrderlD
WHERE 0.CustomerlD = ?
SELECT OrderlD, ProductIO, UnitPrice, Quantity FROM [Order Details]
WHERE OrderlD IN (SELECT OrderlD FROM Orders WHERE CustomerlD = ?)
SELECT D.OrderlD, D.ProductlD, D.UnitPrice, D.Quantity
FROM [Order Details] D, Orders 0
WHERE D.OrderlD = 0,OrderlD AND 0.CustomerlD = ?

SQL Query Analyzer, , SQL


Server , . -,
. -, Data Adapter Configuration Wizard
- .
, INNER JOIN,

, SQL-
. .
OleDbDataAdapater,
daDetails.
DataTable Order Details
DataSet
DataAdapter Order Details, Generate Dataset DataSet
DataTable. . 13-"?,
DataSet . , .
DataAdapter.
, Visual Studio .NET DataTable
DataSet . , Visual Studio .NET DataTable Orders,
DataSet . , AutolncrernentSeed \\AutoIncrementStep . , .
, DataSet
DataTable, Orders Order Details,

13 Windows-

503

DataRelation, DataTable
OrderlD. Solution Explorer .xsd-
, XML Schema Designer.
CustomerlD DataTable Orders DataTable Order Details. .

Genate a dataset that inekjdes ?he specified tables,


Choose a dataset:
* Enisling fchapteri 3. ifsdCbapterTs
f" IJtew:

I,' '--''.

Cfioose which tablets) to add tothedataset:

Orders (daOrders)

'& fidd Ehhctataset to the designer.

Cancel

Help

. 13-7. DataTable Order Details


DataSet
, , ,
DataTable Order Details . Decimal Expression UnitPrice 'Quantity.
.

DataGrid,
DataGrid .
DataSource DataMember,
DataGrid gridDetails.
Properties DataSource. , .
DataSet DataTable. DataMember.
(. 13-8).
DataTable Orders, DataRelation.
DataMember DataRelation, DataGrid , DataRelation.
DataGrid ,
:

504

IV ADO.NET

Visual Basic .NET


gridDetails.DataSource = dsChapter13
gridOetails.DataMemtier = "Orders. Order_x0020_Details'
Visual C# .NET
gridDetails.DataSource = dsChapter13;
gridDetails. DataHember = "Orders. Orcter_x0020_Details'
Properties

9. x
>yst em. Windows, Forms, DataGi f\

cdumnHeaderiVisibli True
\ ContextMenu
(none)
_H0020_Petaib
Order Details
- |Tj Orders

: GndLineCalor
GridLine5tyle
HeaderBackColar
S.Headeifont
HeaderForeCobr
ImeMode

^] Control
5oiid
|_J Control
Microsoft Sans 5er(f, 3
^| ControlText
No Control

. 13-8. DataMember
DataGrid,
, , Load ,
, FormatDetailsGrid.
DataGrid DataGrid'iableStyle,
: ,
, .

11 . , ,
( , ), ( , ). ,
DataAdapter.Update DataTable.
. Order Details. . , Click Submit Changes,
, . , Try/Catch.

13

Windows-

505

Visual Basic .NET


Dim intOrdersModified, intDetallsModified As Integer
Dim aRowsToUpdate As DataRow()

Dim dvrs As DataViewRowState


'
dvrs = DataViewRowState.Added Or DataViewRowState.ModifiedCurrent
aRowsToUpdate = dsChapter13.Orders.SelectC"", "", dvrs)
intOrdersModified = daOrders.Update(aRowsToUpdate)
' DataTable,
' Order Details
intDetailsModified = daDetails.Update(dsChapter13.0rder_Details)
'
dvrs = DataViewRowState.Deleted
aRowsToUpdate = dsChapter13.Orders.Select("", "", dvrs)
intOrdersModified += daOrders.Update(aRowsToUpdate)
Dim strOutput As String
strOutput = "Modified " & intOrdersModified & " order(s)" & vbCrLf & _
"Modified " & intOetailsHodified & " detail(s)"
MessageBox.Show(strOutput, "Update succeeded!",
MessageBoxButtons.OK, MessageBoxIcon,Information)

Visual C# .NET
int intOrdersHodified, intDetailsModified;
DataRow[] aRowsToUpdate;
DataViewRowState dvrs;
//
dvrs = DataViewHowState.Added ] DataViewRowState.ModifiedCurrent;
aRowsToUpdate = dsChapter13.Orders.SelectC'", "", dvrs);
intOrdersModified = daOrders.Update(aRowsToUpdate);
// DataTable,
// Order Details
intDetailsModified = daDetails.Update(dsChapter13.0rder_Details);
//
dvrs = DataViewRowState.Deleted;
aHowsToUpdate = dsChapter13.Orders.SelectC'", "", dvrs);
intOrdersModified += daOrders.Update(aRowsToUpdate);
string strOutput;
strOutput = "Modified " + intOrdersModified + " order(s)\n\r" +
"Modified " + IntDetailsHodified + " detail(s)";
MessageBox.Show(strQutput, "Update succeeded!",
MessageBoxButtons.OK, MessageBoxIcon.Information);

9.


, .
, , , ,

506

IV ADO.NET

DataGrid . .
- ,
DataGrid. , ,
, DataGrid ,
Escape Ctrl+Z, ,
.
, , ,
. , 9
DataGrid . ,
,
. , (. 13-9),
.

. 13-9.

, ,
Update Cancel.
, , . Text Box
, DataGrid . , ,
.
, Edit,
DataGrid, ,
EditDetail . Currency Manager.
EditDetail . , CurrencyManager, TextBox
. Current CurrencyManager
DataRowView. TextBox DataView,
DataView DataRowView DataView. DataRowView,

13

Windows-

Visual Basic .NET


Dim drvDetail As DataRowView
Dim vueDetail As DataView
Public Sub EditDetail(ByVal cm As CurrencyManager)
drvDetail = CType(cm.Current, DataRowView)
vueDetail = drvDetail.DataView
Me.BindingContext(vueDetail).Position = cm.Position
txtOrderID,DataBindings.Add("Text", vueDetail, "OrderlD")
txtProductID.DataBindings.Add("Text", vueDetail, "ProductID")
txtUnitPrice.DataBindings.Add("Text", vueDetail, "UnitPrice")
txtQuantlty.DataBindings.Add("Text", vueDetail, "Quantity")
txtltemTotal.DataBindings.Add("Text", vueDetail, "ItemTotal")
If He.ShowDialog = DialogHesult.OK Then
cm.EndCurrentEditO
Else
cm.CancelCurrentEdit()
End If
End Sub

Visual C# .NET
DataRowView drvDetail;
DataView vueDetail;
public void EditDetail(CurrencyManager cm)
{
drvDetail = (DataRowView) cm.Current;
vueDetail = drvDetail.DataView;
this.BindingContext[vueDetail].Position = cm,Position;
txtOrderID.DataBindings.Add("Text", vueDetail, "OrderlD");
txtProductID.DataBindings.Add("Text", vueDetail, "ProductID");
txtUnitPrice.DataBindings.Add("Text", vueDetail, "UnitPrice");
txtQuantity.DataBindings.AddC'Text", vueOetail, "Quantity");
txtItemTotal.DataBindings.Add{"Text", vueDetail, "ItemTotal");
if (this.ShowDialogC) == DialogResult.OK)
cm. EndCurrentEditO;
else
cm. CancelCur rentEditO;

507

508

IV ADO.NET

10.

, - ,
.
, ,
. , ,
, , , .
, .
, (. 13-).

. 13-.


ComboBox
. 13-10 TextBox,
EmployeelD , ComboBox, .
ComboBox.
ComboBox
, DataAdapter,
Employees. :
SELECT EmployeelD, LastName +
FROM Employees

* FirstNarne AS EmployeeName

DataAdapter ,
DataSet
DataTable Employees.
, ComboBox EmployeeName DataTable Employees.

13

Windows-

509

, Combo Box EmployeelD


EmployeelD .
ComboBox DataTable Employees .
Employees,
DataAdapter, Employees, .
,
SQL Statement Advanced Options.
, ComboBox DataTable Employees. ComboBox DataSource, , DataGrid. DataSet,
DisplayMember , ComboBox , .
EmployeeName DataTable Employees. ValueMember EmployeelU DataTable Employees.
, , ComboBox
EmployeelD .
Text TextBox DataSet. Properties (DataBindings), . SelectedValue EmployeelD DataTable Orders,
:
Visual Basic .NET
cboEmployee.DataSource = dsChapter13
cboEmployee,DisplayMember = "Employees.EmployeeName"
cboEmployee.ValueMember = "Employees.EmployeelD"
cboEmployee,DataBindings.AddC'SelectedValue", dsChapter13,
"Orders.EmployeelD")

Visual C# .NET
cboEmployee.DataSource = dsChapter13;
cboEmployee.DisplayMember = "Employees.EmployeeName";
cboEmployee.ValueHember = "Employees.EmployeelD";
cboEmployee. DataBindings. AddC'SelectedValue", dsChapteMS,
"Orders.EmployeelD");

EmployeeName, EmployeelD. ,
EmployeelD, ,
ComboBox,

UnitPrice DataSet Decimal. ,
TextBox ,

IV

510

ADO,NET

UnitPrice,
. , S4-50.
TextBox 45 ,
.
, Text TextBox DataView.
Visual Basic .NET
txtOrderID.DataBindings.Add("Text", dsChapter13, "Orders.OrderlD")
Visual C# .NET
txtOrderID.DataBindings.Add("Text", dsChapter13, "Orders.OrderlD");

Add Binding,
CurrencyManager TextBox
, ,
Binding Format Parse. Format
, Binding , . Parse , Binding
.
TextBox.
UnitPrice
TextBox ,
currency.
ToString Decimal
Visual Basic .NET
Public Sub EditDetail(ByVal cm As CurrencyManager)
Dim b As Binding
b = txtUnitPrice.DataBlndings.Add("Text", vueDetail, "UnitPrice")
AddHandler b.Format, AddressOf DecimalToCurrencyString
AddHandler b.Parse, AddressOf CurrencyStringToDecimal
End Sub

Private Sub DecimalToCurrencyString(ByVal sender As Object,


ByVal cevent As ConvertEventArgs)
If Not cevent.DesiredType Is GetType(String) Then
Exit Sub
End If
If cevent.Value Is DBNull.Value Then
cevent.Value = CDec(0).ToString("c")
Else
cevent.Value = CDec(cevent.Value).ToString("c")

13

Windows-

End If
End Sub

Private Sub CurrencyStringToDecimal(ByVal sender As Object,


ByVal cevent As ConvertEventArgs)
If Not cevent. DesiredType Is GetType(Decimal) Then
Exit Sub
End If
cevent. Value = Decimal. Parse(cevent. Value. ToString,
Globalization. NumberStyles. Currency,
Nothing)
End Sub

Visual C# .NET
public void EditDetail(CurrencyManager cm)
Binding b;
b = txtUnitPrice.DataBindings.Add( T Text", vueDetail, "UnitPrice");
b. Format += new ConvertEventHandler(DecimalToCurrencyString);
b. Parse += new ConvertEventHandler(CurrencyStringToDecimal);

private void DecimalToCurrencyString(object sender,


ConvertEventArgs cevent)
{
if { I cevent. DesiredType. Equals(typeof (string)))
return;
if (cevent. Value == DBNull. Value)
cevent. Value = ((Decimal) 0).ToString("c");
else
cevent. Value = ((Decimal) cevent. Value). ToStrlngC'c");
I

private void CurrencyStringToDecimal(object sender,


ConvertEventArgs cevent)

if (! cevent. DesiredType. Equals(typeof( Decimal)))


return;
cevent. Value = Decimal. Parse(cevent. Value. ToStringO,
System. Globalization. NumberStyles. Currency,
null);

51 1

512

IV

ADO.NET

11. - ...
.
,
DataTable,
.
.


DataSet. 10 , TextBox. -, 10 , ,
Null. ,
, : , .
. 10 - , , . , Edit Detail TextBox, Quantity Price,
TextBox ItemTotal. ,
TextBox
ItemTotal TextBox, Quantity Price. Text
TextBox ItemTotal Leave
TextBox, Quantity Price.
CurrencyManagerRefresh. CurrencyManager.SuspendBinding CurrencyManagerResumeBinding. ,
. , , .
,

,
.
.
, . 11 TextBox . Edit Orders, SbowCurrentOrder, , ,
DataView. ,
, TextBox.

13 Windows-

513

,
, .

:
,
, Windows Forms,
. , , , , .
, .


- Windows-.
, .



. SELECT..FROM ,
. , .
. . ? . ,
? , ,
?
, , , .
28 /, ,
. ,
,

.


- .

514

IV

ADO.NET


,
, .
, - . ADO.NET Submit Change.
, Update. Edit,
. Cancel, . Update , ,
DataAdapter .
, .
, , , ,
, .
* , -
. -
, ,
. , , , . , , , , ,
.

, DataSet, .
, DataSet .
, -
DataSet. , ,
. , .
-. .
Edit -
. , ,

.
, , Edit, . , , Edit
.
DataAdapter,
:
SELECT ,

. FROM WHERE = ?

13 Windows-

515

PrimaryKey DataTable , DataAdapter DataRow, . : ,


. .
DataAdapterFill ,
. Fill 0, . .
ADO.NET
, , , , . .
!
. . .
, -
. ,
.

, . ,
- .

, '. , -
, . ADO.NET
. ] 0 11, DataAdapter DataSet. DataRow, DataSet . ADO.NET, , , .
, Transaction.
, SELECT.
SELECT , ,
.
, ,
, , .
SQL Server Read Committed (
). , ,
.

516

IV ADO.NET

SELECT . Repeatable Read ( ) Scrializable (), SELECT.


.
SQL Server
:
SELECT CustomerlD, CompanyName, ContactName, Phone FROM Customers
WITH (UPDLOCK) WHERE CustomerlD = 'ALFKI'


.
OleDbTransaction
, SELECT, MSDE. ,
.
DataAdapterJFill .
, SQL Server Query Analyzer, .
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Oata Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT CustomerID, CompanyName FROM Customers " &
"WITH (UPDLOCK) WHERE CustomerlO = 'ALFKI'" '
Dim en As New OleDbConnection(strConn)
en.Open()
Dim txn As OleDbTransaction = cn.BeginTransaction
Dim cmd As New 01eDbCommand(strSQL, en, txn)
Dim da As New OleDbDataAdapter(cmd)
Dim cb As New OleDbCommandBuilder(da)
Dim tbl As New DataTableO
da.Fill(tbl)
Dim row As DataRow = tbl.Rows(O)
row("CompanyName") = "Modified"
da.Update(tbl)
txn.RollbackQ
cn.CloseO

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
StrSQL = "SELECT CustomerlD, CompanyName FROM Customers " +
"WITH (UPDLOCK) WHERE CustomerlD = 'ALFKI'";
OleDbConnection en = new QleDbConnection(strConn);
cn.0pen();

13 Windows-

517

OleDbTransaction txn = cri.BeginTransactionO;


OleDbCommand cmd = new OleDbCommandCstrSQL, en, txn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
OleDbCommandBuilder cb = new OleDbCotnmandBuilder(da);
DataTable tbl = new DataTableO;
da.Flll(tbl);
DataRow row = tbl.Rows[0];
row["CompanyName"] = "Modified";
da.Update(tbl);
txn.Rollback();
cn.Close{);
CommandButtder
.
11.


, .

DataAdapter .
. DataAdapter fill DataAdapter.Update DataAdapter
, ,
, .

.
,
.
. , , . ,
, . , .
. . ,
DataAdapter . :

Visual Basic .NET


daProducts.Fill(dsChapter13.Products)
daEmployees.Fill(dsChapter13.Employees)
daOrders.SelectCommand.Parameters(O).Value = strCustomerlD
daOrders.Fill(dsChapteM3. Orders)
daDetails.SelectCommand.Parameters(O). Value = str Customer-ID
daDetails.Fill(dsCnapter13.0rder_Details)

518

IV

ADO.NET

Visual C# .NET
daProducts.Fill(dsChapter13.Products);
daEmployees.Fill(dsChapter13.Employees);
daOrders.SelectCommand.Parameters[0].Value = strCustomerlD;
daOrders.Fill(dsChapter13.Orders);
daDetails.SelectCommand.Parameters[Q].Value = strCustomerlD;
daDetails.Fill(dsChapter13.0rder_Details)
DataAdapterfill
DataAdapter Connection. , Connection. .
DataAdapterfill, -
. , Connection DataAdapter, , ,
.
, , , .


. , , , , , .
, ,
.
.
, ,
, .
,
. ,
.
, . -
Connection, . , ,
Connection, .
OLE DB .NET Data Provider
, )' :
OLE OB Services=-4;

SQL Client .NET Data Provider, :


Pooling=False;

13 Windows-

519



(BLOB-) , . . . . SQL Server 2000 BLOB- 8 . , 40
.
- BLOB- , .
. .
BLOB- , ADO.NET.
BLOB-
, , BLOB. ? SQL Server BLOB- 2 . , BLOB- ?

BLOB- , . , BLOB. ,
BLOB- ,

BLOB- DataSet
BLOB- DataSet . ADO.NET BLOB , . DataRow
Get-Chunk \\nnAppendChunk. .
BLOB- ,
.
Visual Basic .NET
Dim row As DataRow
Dim strBlob As String
' BLQB-
strBlob = CStr(row("TextBlob"))
' BLOB-
rowC'TextBlob") = strBlob

520

IV ADO.NET

Visual C# .NET
DataRow row;
string strBlob;
// BLOB-
strBlob = (string) row["TextBlob"];
// BLOB-
row["TextBlob"] = strBlob;
BLOB- , ,
.
Visual Basic .NET
Dim row As DataRow
Dim aBinaryBlob As ByteO
' BLOB-
aBinaryBlob = CType(row("BinaryBlob"), ByteO)
' BLOB-
row("BinaryBlob") - aBinaryBlob

Visual C# .NET
DataRow row;
Byte[] aBinaryBlob;
// BLOB-
aBinaryBlob = (Byte[]) row["BinaryBlob"];
// BLQB-
row["BinaryBlob"] = aBinaryBlob;
BLOB- DataReader
DataReader : - .
BLOB-,
DataReader.
Visual Basic .NET
Dim
Dim
Dim
Dim
Dim

end As OleDbCommand
rdr As OleDbDataReader
intTextBlobColumnNo, intBinaryBlobColumnNo As Integer
strTextBlob As String
aBinaryBlob As ByteO

rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
Do While rdr.Read
StrTextBlob = rdr.GetStringfintTextBlobColuinnNo}
aBinaryBlob = CType(rdr(intBinaryBlobColumnNo), ByteO)
Loop
rdr,Close

13 Windows-

521

Visual C# .NET
OleDbCommand cmd;
OleDbDataReader rdr;
int IntTextBlobColumnNo, intBinaryBlobColumnNo;
string strTextBlob;
Byte[] aBinaryBlob;
rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (rdr.Readf))
{
strTextBlob = rdr.GetString(intTextBlobColumnNo);
aBinaryBlob = (Byte[]) rdr[intBinaryBlobColumnNo];
I

rdr.CloseO

-, GetString .
- . DataReader GetBytes, , .
- .
- ,
. -, ,
.
DataReader , GetBytes GetChars, . GetBytes DataReader -
8 . , - GetCbars.
Visual Basic .NET
'
Imports System.10
Dim cmd As OleDbCommand
Dim rdr As OleDbDataReader
Dim intBlobColumnNo As Integer = 1
Dim intChunkSize As Integer = 8192
Dim intOffset As Integer = 0
Dim intBytesReturned As Integer
Dim aBinaryBlob(intCnunkSize) As Byte
Dim strPathToFile As String = "C:\GetBytes.jP9"
Dim filOutput As New FileStreamfstrPathToFile, FileMode.Create)
rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess)

522

IV ADO.NET

rdr.Read()
Do

intBytesReturned = CInt(rdr.GetBytes(intBlobColumnNo, intOffset, _


aBinaryBlob, 0, intChunkSize))
If (intBytesReturned > 0) Then
filOutput.Write(aBinaryBlob, 0, intBytesReturned)
End If
intOffset += intBytesReturned
Loop Until intBytesfleturned intChunkSize
filOutput.Close()
rdr.CloseO

Visual C# .NET
//
using System.10;
QleubCommand cmd;
OleDbDataReader rdr;
int intBinaryBlobCol = 1;
int intChunkSize = 8192;
int intOffset = 0;
int intBytesReturned;
Byte[] aBinaryBlob = new Byte[intChunkSize];
string strPathToFile = "C:\XGetBytes.jpg";
FileStream filOutput = new FileStream(strPathToFile, FlleMode.Create);
rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
rdr.ReadC);

do
{

intBytesReturned = (int) rdr.GetBytes(intBinaryBlobCol, intOffset,


aBinaryBlob, 0, intChunkSize);
if (intBytesReturned > 0)
filOutput.Write(aBinaryBlob, 0, intBytesReturned);
intOffset += intBytesReturned;
1 while (intBytesReturned == intChunkSize);
filOutput. CloseO;
rdr.CloseO;
BLOB- Northwind
, , , Northwind BLOB-. ,
Employees Photo, .
, Photo , OLE- Access. Access
, - .jpg-, Word,
Excel .. ,
Photo ADO.NET ( ADO, RDO .), PictureBox
, Paint.

13

Windows-

523

OLE- Access .
, OLE- Access
Microsoft, .
-
LoadEmployeePhotos,
Photo Employee .jpg. .jpg- . 1 Northwind, .
,
,
BLOB-
, Employees , ,
Windows-. ShowEmpfoyeesPhotos (. 13-11),
-,
Northwind DataSet.

. 13-11.

BLOB- PictureBox

CurrencyManager
, .
DataSet
DataTable: BLOB- .
DataTable (EmployeelD),
DataTable
DataTable. , DataTable FetchedPhoto, , .

( EmployeelD, LastName, FirstName ..). , -

524

IV

ADO.NET

, - Photo, ( 22 . , , ,
). ,
.

,
ADO.NET
, Windows- . ,
,
, . , , , BLOB-.

,
. ,
?
. , .
,
, , , . ,
, , ,
,
,
11 -, , DataGrid.
, DataGrid, , DataGrid ,
.
. DataSet ?
. . DataSet , . , ,
DataSet ,
DataSet .

13

Windows-

525

Visual Basic .NET


' TextBox DataColumn
TextBox.DataBindings.Add{"Text", DataSet, "TableName.ColumnName")
' DataGrid DataTable
DataGrid.DataSource = DataSet
DataGrid.DataMember = "TableName"

Visual C# .NET
// TextBox DataColumn
TextBox.DataBindings.Add("Text", DataSet, "TableName.ColumnName"};
// DataGrid DataTable
DataGrid.DataSource = DataSet;
DataGrid.DataMember = "TableName";
. . ?
. , . ,
/ . - .NET Framework . .NET Framework SDK.
System-Threading. .NET Framework , Visual Basic, , .
. 11 -
DalaView, DataTahle't
. DataKow , -
Rows DataTable.
, DataTable, , , .
DataView. Roii'StateFilter DataView ,
, , . CurrencyManager .
. ,
?

526

IV

ADO.NET

. ,
. , , .
. , , .
. ,
, ,
. , ,
, ,
.
. , , . ,
SQL Server, .
1. ,
.
2. : , ,
3. , .
, GUID. ,
. :
CREATE PROCEDURE spPessimisticLockAcquirelock
(@ID int, @LockID uniqueidentifier)
AS
UPDATE tblPessimisticLock
SET LockAcquired = GetDateO, LockID = LockID
WHERE ID = ID AND LockAcquired IS NULL

4. , .
, . ,
, .
, .
CREATE PROCEDURE spPessimisticLockUpdateRow
(@ID int, @DescCol varchar(32), @LockiD uniqueidentifier)
AS
UPDATE tblPessimisticLock
SET DescCol = $DescCol
WHERE 10 = OID AND LockID = @LockID
IF @@ROWCOUNT = 1
BEGIN

13

Windows-

527

SET NOCOUNT ON
UPDATE tblPessimisticLock
SET LockAcquired = NULL, LockID = NULL
WHERE ID = SID AND LockID = LockID
END

5. , .
CREATE PROCEDURE spPessimistlcLockReleaseLock

(@ID int, @LockID uniqueidentifier)


AS
UPDATE tblPessimisticLock
SET LockAcquired = NULL, LockID = NULL
WHERE ID = 810 AND LockID = @LockID
6. , .
, 5 , :
UPDATE tblPessimist!Lock
SET LockAcquired = NULL, LockID = NULL
WHERE DateAdcKmi, 5, LockAcquired) <= GetDate{)

14

Web-

11 Windows- , - Web-.

Web-
Web-. ASP.NET
, , , Building Web Solutions with ASP.NET and ADO.NET (Microsoft
Press, 2002.). ,
Web-, ADO.NET. , ASP.NET, .
ASP.NET, , DataGrid.

ASP.NET Web-
Web-, . Web-, HTML-, Web-. , Web- ,
. , Web-

.
ASP.NET Web-. ASP.NET Visual Basic .NET Visual C*.NET.

14

Web-

529

Web- ASP.NET.
Windows- , HTML-. Web- Button ASP.NET Click , ASP.NET Web- HTML-, Web- Click.
, ASP.NET , .
, ASP.NET, ASP.NET, Web-.
ASP.NET. , ,
ASP.NET HTML-
. ,
ASP.NET , ,
(stateless).



ASP.NET- (Vaspx), IIS
ASP.NET, . , ASP.NET . , ASP.NET
. ASP.NET - .
, , ASP.NET, ,
,
.
,
Web- - . Web- . Web ,
, ,
Web-, .
, ASP.NET , DataAdapter
DataTable. ,
DataTable Web- DataGrid,
Web-. , Web- , .
ASP.NET HTML-,
Web-. ASP.NET , DataTable
. Web-
DataTable. ,

530

IV ADO.NET

, , ; , .NET.


, Web-
Windows-. Connection, ,
.



.NET Framework SDK MSDE:
Provider=SQLOLEDB;Data Source=(local)\NetSDK;
Initial Catalog=Northwind;Trusted_Cormection=Yes;
Web-
, . , Load Web- :
Visual Basic .NET
Dim strConn As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleObConnection(strConn)
cn.OpenO
Visual C# .NET
string strConn;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new DleDbConnection{strConn);
cn.OpenO;
Windows Web- :
Login failed for user '\8'
Windows- . Web-? :
, SQL Server
. ,
, , . ASP.XET,
, ASP.NET.
, ASP.NET
SQL Server .

14

Web-

531

SQL Server Enterprise Manager


. Security , Logins New Login. MSDE Enterprise Manager, SQL
Server :
exec sp.grantlogin '\'


, , ?
ASP.NET . Visual Studio .NET
Web-, Solution Explorer \Veb.config.
XML- . :
<authorization>
<allow users="*" />
</authorization>
.
, ,
:
<authorization>
<deny users="?" />
</authorization>
<identity impersonate="true" />
.
Web,
. Web-,
, ,
. , ADO.NET
.
, .
, ,
.
,
, ,
, ASP.NET.

. ASP.NET : Windows, -

532

IV

ADO.NET

Microsoft Passport, Forms.

Access
Access
ASP.NET-. . Access
. SQL Server Oracle. Access
. .
, Access ASP.NET-, . .NET Microsoft ,
ASP.NET. ,
ASP.NET- Access.
Access, Jet ( , ), ,
. , , ,
, . ,
;
The Microsoft Jet database engine cannot open the file
'C:\Path\To\MyDatabase.mdb'. It is already opened exclusively by another
user, or you need permission to view its data.

Operation must use an updateable query.

, ASP.NET
. , ASP.NET
,
Access.

Web-
, .
, Web.
Windows Forms, ASP.NET-
:
Visual Basic .NET
TextBoxl.Text = MyDataSet.Tables("MyTable").Rows(Q)("MyColumn")

Visual C# .NET
TextBoxl.Text = (string) MyDataSet.Tables["MyTable"].Rows[0]["HyColumn"];

14 Web-

533

,
, ASP.NET. , Web- , DataSet. DataSet Web- HTML-. HTML- ,
ASP.NET, XML XSLT,
, ,
ASP.NET.
ASP.NET HTML-
Web-. ASP.NET
. DataTable,
,
DataTable.
DataGrid , Web-
, ASP.NET
, .
Windows, , , , . DataSource DataMernber.
DataBinder Web-,

DataBinder.Eval
, ASP.NET,
, TextBox,
Eval DataBinder. DataBinder
Reflection. ,
Company-Name DataTable:
DataBinde.Eval(DataTable,

"Rows[0],[CompanyName]")

Eval
Object, .
Eval . Eval, . , .
Eval UnitPrice currency:
DataBinder. EvaKDataTable, "Rows[0]. [UnitPrice]", "{0:c}")
Eval .
StringFormat.
DataBinder . ,
Visible TextBox:

534

IV

ADO.NET

DataBinder.Eval(TextBox1,

"Visible")

Visible
TextBox , DataBinder
.
:
DataBinder.Eval(TextBox1, "Visibile")
, ,
, ' DataBinder
, , ,
.
TextBox DataSet
DataBinder, TextBox ,
DataAdapter, Customers
DataSet DataBinder Text
TextBox CompanyName , :
Visual Basic .NET
Dim strConn, strSQL, strExpression As String
strConn = "Provider=SQI_OLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT CustomerlD, CompanyName FROM Customers " &
"WHERE CustomerlD = 'WOLZA'"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New DataSet()
da.Fill(ds, "Customers")
strExpression = "Tables[Customers].Rows[0].[CompanyName]"
TextBoxl.Text = CStrfDataBinder.Eval(ds, strExpression))

Visual C# .NET
string strConn, strSQL, strExpression;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT CustomerlD, CompanyName FROM Customers " +
11
"WHERE CustomerlD = 'WOLZA ';
OleDbDataAdapter da = new 01eDbDataAdapter(strSOL, strConn);
DataSet ds = new DataSetO;
da.Fill(ds, "Customers");
strExpression = "Tables[Customers].Rows[0].[CompanyName]";
TextBoxl.Text = (string) DataBinder.Eval(ds, strExpression);

14 Web-

535

TextBox DataReader
DataBinder DataReader. DataReader. ,
SingleRow CommandBehavior-.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLED8;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trijsted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
cn.0pen()
strSQL = "SELECT CustomerlD, CompanyName FROM Customers " &
"WHERE CustomerlD = 'WOLZA'"
Dim cmd As New 01eDbCommand(strSQL, en)
Dim rdr As OleDbDataReader
rdr = cmd.ExecuteReader(CommandBehavior.SingleRow)
rdr.ReadC)
TextBoxl.Text = CStr(DataBinder.Eval(rdr, "[CompanyName]"))
rdr.Close()
cn.CloseO

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
cn.0pen();
strSQL = "SELECT CustomerlD, CompanyName FROM Customers " +
"WHERE CustomerlD = 'WOLZA'";
OleDbCommand cmd = new 01eDbCommand(strSQL, en);
OleDbDataReader rdr;
rdr = cmd.ExecuteReader(CommandBehavior.SingleRow);
rdr.fleadO;
TextBoxl.Text = (string) DataBinder.Evalfrdr, "[CompanyName]");
rdr.CloseO;
cn.CloseO;

DataGrid

AS P. NET DataGrid, HTML-. , , . , DataGrid .

536

IV ADO.NET

DataGrid DataSet
OleDbDatoAdapter DataSet, DataSet DataGrid
Web- DataTable DataSet.

Visual Basic .NET


Dim strConn, strSQL As String
strConn = "Provlder=SQLOLEDB;Data Source=(local)\NetSDK; " &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Phone " &
"FROM Customers"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New DataSetO
da.Fill(ds, "Customers")
gridCustomers.DataSource = ds
gridCustomers.DataMember = "Customers"
g ridCustomers. DataBlndO
Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT CustomerlD, CompanyNafoe, ContactName, Phone " +
"FROM Customers";
OleDbDataAdapter da = new OleDbDataAdapterfstrSQL, strConn);
DataSet ds = new DataSetO;
da.Fill(ds, "Customers");
gridCustomers.DataSource = ds;
gridCustomers.DataMember = "Customers";
gridCustomers.DataBind();

DataGrid
Windows- DataSet , . DataSource DataMember, DataBind DataGrid. Windows- DataGrid .
Web- . DataGrid DataBmd . ,
DataBind ; .

DataGrid DataReader
, Web- .
DataSet ( , .),
Web. ASP.NET
DataReader.

14

Web-

537

, OleDbDataReader DataGrid Web-.


Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT Customer-ID, CompanyName, ContactName, Phone " &
"FROM Customers"
Dim en As New OleDbConnection(strConn)
cn.0pen()
Dim cmd As New 01eDbCommand(strSQL, en)
Dim rdr As OleDbDataReader = cmd.ExecuteReader()
gridCustomers.DataSource = rdr
g ridCustomers.DataBindC)
rdr.Close()
cn.Close()

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT CustomerlO, CompanyName, ContactName, Phone " +
"FROH Customers";
OleDbConnection en = new OleDbConnection(strConn);
cn.OpenO
OleDbCommand cmd = new 01eDbCommand{strSQL, strConn);
OleDbDataReader rdr = cmd.ExecuteReader();
gridCustomers,DataSouroe = rdr;
gridCustomers. DataBindO;
rdr.CloseC);
cn.CloseO;


, Web-, ,
HTML- ,
. ,
? , ,
. .
ASP.NET , , .
. .
, , .

538

IV

ADO.NET

,
,
, .
Application *,
, ASP.NET.


, , .
ASP.NET- Web- .
HTML . ,
, ,

.

: ASP.NET- ,
.
.

. , , .
, ?


, .

cookie
Web- cookie. Request Response ASP.NET
cookies,
. , cookie :
Visual Basic .NET
If Request.Cookies("LastVisit") Is Nothing Then
IblLastVisit.Text = "This is your first visit! Welcome!"
Response.AppendCookie(New HttpCookie("LastVisit", Now.ToString))

14

Web-

539

Else
IblLastVisit.Text = "Welcome back. Your last visit was: " & _
Request.Cookies("LastVisit").Value
Response.Cookiesf'LastVisit").Value = Now.ToString
End If

Visual C# .NET
if (Request.Cookies["LastVisit"] == null)
{
IblLastVisit.Text = "This is your first visit! Welcome!";
Response.AppendCookie(new HttpCookieC'LastVisit",
DateTime.Now.ToStringO));
}
else
{
IblLastVisit.Text = "Welcome back. Your last visit was: " +
Request.Cookies["LastVisit"].Value;
Response.Cookies["LastVisit"].Value = DateTime.Now.ToStringO;
!

ASP.NET cookie. ASP.NET- ,


. , cookie . cookie Expires
HttpCookie.

cookie .
cookie ,
,
, .
, - cookie. . ,
cookie .
cookie .
.

Web-.
- Windows-.
ASP.NET - .
,
, ,
ViewState.

IV ADO.NET

540

ViewState
Page System.Web.fJI ViewState,
StateBag. ,
, Cookies Request Response,
,
ViewState , , .
ViewState , cookie:
Visual Basic .NET
If ViewState("LastVisit") Is Nothing Then
IblLastVisit.Text = "This is your first visit! Welcome!"
ViewStateC'LastVisit") = Now.ToString
Else
IblLastVisit.Text = "Welcome back. Your last visit was: " & _
ViewStateC'LastVisit")
ViewStateC'LastVisit") = Now.ToString
End If
Visual C# -NET
if <ViewState["LastVisit"] == null)

IblLastVisit.Text = "This is your first visit! Welcome!";


ViewState["LastVisit"] = DateTime.Now.ToStringO;

i
else
{

IblLastVisit.Text = "Welcome back. Your last visit was: " +


ViewState["LastVisit"];
ViewState["LastVisit"] = DateTime.Now.ToStringO;

at a naine="'3Ei4ERAT.JR ' cent e-rt -'Micrcsc-t visual studio.NET 7 . 0 "


conteim-"http: //schemes. 4i1crD5oft.com/1meni sense/1
body MS^PQSITIONING-"Gr1dLayOUl:">

driput 11 type-"Mdden" name-11 __ VIEMSTATE"


alue. db*tMTU30DAzNTQ4MDtOPsPGk8MT47Pjt5pHqeo;w8aTwxP]s+o;8dDi"PHABQDxu2xhOOZ47bDx>ZVix1b;ni

LEFT: 22p; POSITION: absolute; TOP: 24px">wel


!</1>
</fcnr>
</body>

helghT-.27ps;w(dth:419px;7-TNDEX: 101;
aaek. Your lasi visit was: 3/22/2002 1:59:19

|</HTHL>

. 14-1.

ViewState

14 Web-

541

. 14-1 ,
ViewState . HTML- , , ViewState .
, ViewState ,
cookie .

cookie,
ViewState ASP.NET- . ViewState ,
. , cookie, ViewState
.

, ViewState , ,
,
. , , ViewState
, , . , ViewState
.
ViewState , ,
ASP.NET . , , Object , ASP.NET . ViewState , ISerializable, DataSet
DataTable.

Web-
ASP.NET Web-.
Session
Page Session, HttpSessionState.
ViewState. Session
. , HTML- .
ASP.NET , Session, . ,
. ,
Session .

542

IV

ADO.NET

Web-, , .
Session. ,
, Session
.

Session ASP.NET, .
, , Session, ,
. , . 5 ?
50? 500? ,
Web-. J 0 ? 100? 1000? ? , Session.
Application
Application Session , ,
Application ,
. , Application .

Session, Application
. ,
Application .
Application , , , .

Application , .
Cache
Page Cache, Cache.
Cache Application .
Cache .
Cache, Application,
Cache Add Insert,
:
, (DateTime) (TimeSpan) ;

14 Web-

543

CacbeDependancy, .
CacbeDependancy,
XML-;
, ASP.NET
;
Cache ,
Application, , .

, Web- . , . , .
DataSet Application. , ASP.NET- . , , - DataSet HTML-.
ASP.NET : . , .
. HTML- , ASP.NET.

HTML-
DataSet, ,
. Cache,
.

, .


, Web-. , . Web-, .
,
,
, , . ,
CD-RW 2 ,

544

IV ADO.NET

USB FireWire ,
, 30 . :
SELECT ProductID, ProductName, Description, UnitPrice, ... FROM Products
WHERE UnitPrice < 200 AND Description LIKE ' AND
Description LIKE 'XFireWire*' AND ...

, 50 , 10 . , , . INSERT INTO ,
, ,
:
INSERT INTO ProductsQueryCache
SELECT ? AS SessionID, ProductID, ProductName, Description, UnitPrice, ...
FROM Products
WHERE UnitPrice < 200 AND Description LIKE 'MSB*' AND
Description LIKE 'XFireWireX 1 AND ...

,
.
, ,
, ,
.
,
End Session
.

ASP.NET-
. , , . Web- - , .
, ASP.NET-. . , .

, Session, Application, Cache, ViewState cookie,

14 Web-

545


, ,
, Web-.
, , Web-
, , . .
, .
ViewState
ViewState, .
, Session . : ViewSession
. ViewSession, .
Application
Application , . : Application, .
Session
Session ,
, ,
ViewState . . :
Session, Application . ,
100 Session. ,
ASP.NET !
, , ,

, , , ,
, , ,
. ,
, ,
, .


HTML-,
ASP.NET, ,
HTML-.

546

IV ADO.NET


, Web-.
. , .
, , . , , ,
- .
- ?
ASP.NET ADO.NET
, .

,
Web- DataGrid
Web- DataGrid ,
. AllowPaging PagerStyle ,
, DataGrid. . 14-2 Web-,
DataGrid
.

. 14-2. Web-,
, DataGrid
, Web- Visual Studio .NET,
Property Builder
DataGrid. , Web- -

14

Web-

547

DataGrid Property Builder.


Paging. , . 14-3.

. 14-3-
DataGrid Property Builder

AltowPaging
Allou'Paging True,
DataGrid ,
AllowPagmg True,
DataGrid
.
Next ( ) Previous ( ) , .
, PagelndexChanged DataGrid. ,
,
CurrentPagelndex DataGrid.
AHowCustomPaging VirtualltemCount
, , , DataGrid . AllowCustomPaging
DataGrid True, VirtualttemCount
DataGrid , .
DataGrid , VirtualltemCount, .
DataReader
10 -

548

IV

ADO.NET

DataGrid .
Visual Basic .NET
gridResults.Allow/Paging = True
gridResults.AllowCustomPaging = True
gridResults.CurrentPagelndex = 0
gridResults.PageSize = 10
gridResults.PagerStyle.Mode = PagerMode.NumericPages
gridResults.PagerStyle.Position = PagerPosition.TopAndBottom
Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim cnNorthwind As New OleDbConnection(strConn)
StrSQL = "SELECT COUNT(CustomerlD) FROM Customers"
Dim cmdFetchRowCount As New 01eDbCommand(strSQL, cnNorthwind)
strSQL = "SELECT TOP 10 CustomerlD, CompanyName, ContactName, Country " & _
"FROM Customers"
Dim cmdFetchOnePage As New 01eDbCommand(strSQL, cnNorthwind)
cnNorthwind.Open()
grldResults.VirtualltemCount = cmdFetchRowCount.ExecuteScalarQ
Dim rdrOnePage As OleDbDataReader = cmdFetchOnePage.ExecuteReader()
gridResults.DataSource = rdrOnePage
gridResults.DataBind()
rdrOnePage.CloseO
cnNorthwtnd.CloseO

Visual C# .NET
gridResults.AllowPaging = true;
gridResults.AllowCustomPaging = true;
gridResults.CurrentPagelndex = 0;
gridResults.PageSize = 10;
gridResults.PagerStyle.Mode = PagerMode.NumericPages;
gridResults.PagerStyle.Position = PagerPosition.TopAndBottom;
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection cnNorthwind = new OleDbConnection(strConn);
strSQL = "SELECT COUNT(CustomerlD) FROM Customers";
OleDbCommand cmdFetchRowCount = new 01eDbCommand(strSQL, cnNorthwind);
strSQL = "SELECT TOP 10 CustomerlD, CompanyName, ContactName, Country " +
"FROM Customers";
OleDbCommand cmdFetchOnePage = new 01eDbCommand{strSQL, cnNorthwind);
cnNorthwind.OpenO;
gridResults.VirtualltemCount =
Convert.ToInt32(cmdFetchRowCount.ExecuteScalarQ);

14 Web-

549

OleDbOataReader rdrOnePage = cmdFetchOnePage.ExecuteReader();

gridfiesults.DataSource = rdrOnePage;
gridResults.OataBindO;
rdrOnePage. CloseO;
cnNorthwind.CloseO;
10 , .
, .
?

,
Fill DataAdapter
5, Fill DataAdapter
,
DataAdapter. , ,
.
, 10 . 40 10. DataSet :

Visual Basic .NET


Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwtnd;Trusted_Connection=Yes;"
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Country " & _
"FROM Customers"
Dim da As New 01eDbDataAdapter(strSQL, strConn)
Dim ds As New DataSetO
da.Fill(ds, 40, 10, "Customers")

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" *
"Initial Catalog=Northwlnd;Trusted_Connection=Yes;";
strSQL = "SELECT CustomerlD, CompanyName, ContactName, Country " +
"FROM Customers";
OleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn};
DataSet ds = new DataSetO;
da.Fill(ds, 40, 10, "Customers");

, .
. - , 40 , DataAdapter DataSet.

550

IV

ADO.NET

,
SQL Server Access ,
. ,
10 Customers,
Country CustomerlD:
SELECT TOP 10 CustomerlD, CompanyName, ContactName, Country
FROM Customers
ORDER BY Country, CustomerlD

, .
, 4150 Customers.
SELECT TOP 10 CustomerlD, CompanyName, ContactName, Country
FROM Customers WHERE CustomerlD NOT IN
(SELECT TOP 40 CustomerlD FROM Customers ORDER BY Country, CustomerlD)
ORDER BY Country, CustomerlD

, 40 Country CustomerlD. 10 , ,
Country CustomerlD.
:
SELECT TOP 1, 2,

. . . FROM

WHERE NOT IN
(SELECT TOP FROM ORDER BY
)
ORDER BY

SQL Server, Access NOT IN.


, ,
. , Oracle
.
Oracle ,
rownum. Oracle , rownum . Oracle
, , rownum , ,
. rownum
, ,
, Oracle- 41 50 Customers:
SELECT CustomerlD, CompanyName, ContactName, Country FROM
(SELECT CustomerlD, CompanyName, ContactName, Country,
rownum AS Row_Num FROM
(SELECT CustomerlD, CompanyName, ContactName, Country
FROM Customers ORDER BY Country, CustomerlD)

14

Web-

551

WHERE rownum <= 10)


WHERE ROW_NUM > 40

Oracle. ,
Oracle.

PagingOptions
- Web- PagingOptions.
, .
DataGrid. DataGrid.
ViewState, Session, . , , , , , .

Web-
Web-. Web, ?
Web- , Windows. : Web-, , HTML- .
TextBox
, .
Web-, , , ASP.NET- .
Web-, ,
Web-, . , TextBox. , Update,
? DataSel
- , , ViewState Session? , ? ,
?


DataGrid
. ,
DataGrid Web- , -

552

IV ADO.NET

. Web-,
. 14-4.
2 SbapptiiBCanlfiDaletwse

Mfctoieft Isplnrar

a/floealhostphoppineC jrt/stcro&itinuiubsH.

Kumbtr of Items. 5
Total Cost af Order: $82 00

| Submit Onler ] CoirtnU Shopp.f

Laughing
' Lumberjack

. 14-4.

Web-,

. 14-5-
Property Builder DataGrid
, DataGrid
, ' , . DataGrid Visual Studio .NET
Property Builder. -

14 Web-

553

(. 14-5),
, .
, ,
.

,
DataGrid
, DataGrid
Property Builder , DataGrid.
DataGrid . 14-5 Edit, Update, Cancel
Delete. , Web , 14-6,

Total Cost of Order 00

SubmitOKfer

Conlinue Shopping

. 14-6. Web-, ,
DataGrid
, Edit .
DataGrid .
, EditCommand
DataGrid. ,
Editltemlndex (
) DataGrid .
, DataBind DataGrid, DataGrid
HTML- TextBox, . , DataGrid Update Cancel.

19-5958

554

IV ADO.NET


1 Jpdate,
UpdateCommand DataGrid.
, ,
.
.

DataSet
DataSet UpdateCommand DataRow, DataAdapter.
UpdateCommand , .
DataAdapter.

Visual Basic .NET


Private Sub gridCart_UpdateCommand(ByVal source As Object, _
ByVal e As DataGridCommandEventArgs)
Dim daCart As New OleDbDataAdapterQ
Dim tblCart As New DataTableQ
Dim vueCart As New DataView(tblCart)
vueCart.Sort = "ProductName"
Dim strNewQuantity As String
strNewQuantity = CType(e.Item.Cells(2).Controls(0), TextBox).Text
Dim intlndexToEdit As Integer
intlndexToEdit = vueCart.Find(e.Item. Cells(1). Text)
vueCart(intIndexToEdit)("QuantLty") = Clnt(strNewQuantity)
daCart.Update(tblCart)
End Sub

Visual C# .NET
private void gridCart_UpdateCominand{ object source,
DataGridCommandEventArgs e)
I
OleDbDataAdapter daCart = new OleDbDataAdapterf);
DataTable tblCart = new DataTableO;
DataView vueCart = new DataView(tblCart);
vueCart.Sort = "ProductName";
string strNewQuantity;
strNewQuantity = ((TextBox) e.Item.Cells[2].Controls[0]).Text;
int intlndexToEdit;
intlndexToEdit = vueCart.Find(e.Item.Cells(1).Text);
vueCart[irvtIndexToEdit][ "Quantity"] = Convert,Tolnt32{strNewQuantity);
daCart.Update(tblCart);
I

14

Web-

555

UPDATE
UpdateCommand ,
.
DataSet DataAdapter, UPDATE, :
UPDATE ShoppingCarts SET Quantity = <NewQuantity>

WHERE ProductName = <ProductName> AND ShoppingCartID = <SessionID>

ShoppingCart
- Web- ShoppingCart, Northwind . , , .
Order Details Northwind.
Web- Web-, StoreCartlnDatabase StoreCartlnViewState, .
,
. , StoreCartlnDatabase , StoreCartlnViewState
ViewState.
, , ViewState.

,
. , DataReader ,
, ?
. Web-, , , . DataReader Read
, , DataReader
, .
DataReader DataGrid,
Count Items DataGrid ,
.
, DataReader.
, :
SELECT OrderlD, Customer-ID, OrderDate FROM Orders
WHERE CustomerlD = ?

, , , , , , :

556

IV

ADO.NET

SELECT COUNT(OrderlD) FROM Orders WHERE CustomerlD = ?;


SELECT Order-ID, CustomerlD, QrderDate FROM Orders
WHERE CustomerlD = ?

Visual Basic .NET


Dim strConn, strSQL As String
strConn = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection=Yes;"
Dim en As New OleDbConnection(strConn)
strSQL = "SELECT COUNT(OrderlD) FROM Orders WHERE CustomerlD = ? ; " & _
"SELECT OrderlD, CustomerlD, OrderDate FROM Orders " & _
"WHERE CustomerlD = ?"
Dim cmd As New 01eDbCommand(strSQL, en)
cmd.Parameters.Add("@CustomerID", OleDbType.WChar, 5)
cmd.Parameters.Add("@CustomerID2", OleDbType.WChar, 5)
cmd.Parameters("@CustomerID").Value = "ALFKI"
cmd.Parameters("@CustornerID2").Value = "ALFKI"
cn.OpenO
Dim rdr As OleDbDatafteader = cmd.ExecuteReaderO
rdr.ReadO
If rdr(O) > 0 Tnen
'
rdr.NextResultQ
gridOrders.DataSource = rdr
gridOrders.DataBindO
Else
'
End If
rdr.CloseO
cn.CloseC)

Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection en = new OleDbConnection(strConn);
StrSQL = "SELECT COUNT(OrderlD) FROM Orders WHERE CustomerlD = ?;" +
"SELECT OrderlD, CustomerlD, OrderDate FROM Orders " +
"WHERE CustomerlD = ?";
OleDbCommand cmd = new 01eDbCommand(strSQL, en);
cmd.Parameters,Add("@CustomerID", QleDbType.WChar, 5);
cmd.Parameters.Add("@CustomerID2", OleDbType.WChar, 5);
cmd.Parameters["CustomerID"].Value = "ALFKI";
cmd.Parameters["@CustomerID2"].Value = "ALFKI";
cn.OpenO;
OleDbDataReader rdr = cmd.ExecuteReaderO;
rdr.ReadO;
if (Convert.Tolnt32(rdr[0]) > 0)

14 Web-

557

//
rdr.NextResult();
gridOrders.DataSource = rdr;
gridOrders.Datafiind();

>
else
<
//
}
rdr. CloseC);
cn.CloseO;

, , , , ,
. Web- ?
. . ShoppingCart
. ,
. , ,
,
, .
, WHERE UPDATE
, .
timestamp
WHERE .
, ViewState, Session ,
. DataSet, DataTable,
DataRelation.
DataGrid
?
. DataRcnv GetChtidRows,
DataRow, . DataGrid DataRow .
DataView, ,
DataTable, RowFiUer DataView
, DataView
. , .
DataView , DataTable. DataView Cre&teChildView DataView,
.

558

IV ADO.NET

Visual Basic .NET


Dim dsCustomersOrders As New DataSetf)
Dim vueCustomers, vueOrders As DataView
vueCustomers = New DataView(dsCustomersOrders.Tables("Customers"))
vueCustomers.Sort = "CustomerlD"
Dim intCustomerlndex As Integer = vueCustomers.FindC'ALFKI")
If intCustomerlndex >= 0 Then
'Located the desired parent row
Dim drvCustomer As DataRowView = vueCustomers(intCustomerlndex)
vueOrders = drvCustomer.CreateChildView("CustomersOrders")
gridOrders.DataSource = vueOrders
gridOrders.OataBindO
Else
'
End If
Visual C# .NET
DataSet dsCustomersOrders = new DataSetO;
DataView vueCustomers, vueOrders;
vueCustomers = new DataView(dsCustomersOrders.Tables["Custcnners"]);
vueCustomers.Sort = "CustomerlD";
int intCustomerlndex = vueCustomers.FindC'ALFKI");
if {intCustomerlndex >= 0)
{
//Located the desired parent row
DataRowView drvCustomer = vueCustomers[intCustomerIndex];
vueOrders = drvCustomer,CreateChildViewC'CustomersOrders");
gridOrders.DataSource = vueOrders;
g ridOrders.DataSindQ;
)
else
I

//


.NET

.NET, OLE DB .NET Data Provider.


,
OLE DB .NET Data Provider. , .NET. Microsoft .NET Framework SQL
Client .NET Data Provider. Microsoft ODBC
.NET Data Provider. , Microsoft Oracle Client .NET Data Provider.
, .NET
OLE DB .NET Data Provider.

SQL Client .NET Data Provider


SQL Client ,NET Data Provider
Microsoft SQL Server Microsoft Desktop Engine (MSDE).


OLE DB ODBC, ?, SQL Client .NET Data Provider .
SQL Client .NET Data Provider
, ,
:
SELECT OrderlD, Customer-ID, EmployeelD, OrderD ate
FROM Orders WHERE CustomeriD = @CustomarID

.NET

561

OLE DB .NET Data Provider ?, :


SELECT OrderlD, CustomerlD, EmployeelD, OrderD ate
FROM Orders WHERE CustomerXD = ?

? ,
(OLE DB ODBC),
OLE DB .NET Data Provider
, .
OLE DB ODBC . , .
SQL Client .NET Data Provider ? SQL Server. SQL Server , ?. .
SQL Server OLE DB .NET Data Provider
, SQL Server OLE DB
Provider . SQL Server OLE DB Provider
, SQL Server. SQL Client .NET Data Provider
SQL Server SQL Server. , SQL Client .NET Data
Provider
.
.NET
. , .

SQL Server
SqIConnection
SQL Client .NET Data Provider
SqIConnection. SQL Server MSDE. ConnectionString SqIConnection . SqlConnection.Open-.
Visual Basic .NET
Dim strConn As String
strConn = "Data Source=(local)\NetSDK;Initial Catalog=No rthwind;" &
"Trusted_Connection=Yes;"
Dim en As New SqlConnection(strConn)
cn.OpenQ
cn.CloseO

562

Visual C# .NET
string strConn;
strConn = "Data Source=(local)\\NetSDK;Initial Catalog=N orthwind;" +
"Trusted_Connection=Yes;";
SqlConnection en = new SqlConnection(strConn);
cn.0pen();
en.Close();

, , , , SQL Server MSDE OleDbConnection. ,


Provider^.... , SqlConnection MSDN,
ConnectionString.
SqlConnection ,
OleDbConnection: PacketSize Workstationld. , ConnectionString SqlConnection.


SqIDataAdapter
DatoSet DataTable
SqIDataAdapter.
OleDbDataAdapter, . ,

.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Data Source=(local)\NetSDK;Initial Catalog=No rthwind;" & _
"Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, CustomerlD, OrderDate FROM Or ders " & _
"WHERE CustomerlD = eCustomerlO"
Dim da As New SqlDataAdapter(strSQL, strConn)
Dim param As SqlParameter
param = da.SelectCommand.Parameters.Add("@Cust omerlD", SqlDbType.NChar, 5)
param.Value = "ALFKI"
Dim tbl As New DataTable("Orders")
da.Fill(tbl)

Visual C# .NET
string strConn, strSQL;
strConn = "Data Source=(local)\\NetSDK;Initial Catalog=N orthwind;" +
"Trusted_Connection=Yes;";
strSQL = "SELECT OrderlO, CustomerlD, OrderDate FROM Or ders " +
"WHERE CustomerlD = $CustomerID";
SqIDataAdapter da = new SqlDataAdapter{strSQL, strConn);
SqlParameter param;

.NET

563

param = da.SelectCommand.Parameters,Add("@Cust omerlD", SqlDOType.NChar, 5);


param.Value = "ALFKI";

DataTable tbl = new DataTablef"Orders");


da.Fill(tbl);

SqICommand SqIDataReader
SqICommand ,
SqIDataReader.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Data Source=(local)\NetSDK; Initial Catalog=No rthwind;" &
"Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, CustomerlD, OrderDate FROM Or ders " & _
"WHERE CustomerlD = @CustomerID"
Dim en As New SqlConnection(strConn)
Dim crnd As New SqlCommandCstrSQL, en)
Dim param As SqlParameter
param = cmd.Parameters.Add("@CustomerID", SqiD bType.NChar, 5)
param.Value = "ALFKI"
cn.0pen()
Dim rdr As SqIDataReader = cmd,ExecuteReaderO
Do While rdr.Read()
Console.WriteLine("OrderID = " & rdr.Get!nt32(0))
Console.WriteLine("CustomerlD = " & rdr.GetString(f))
Console.WriteLine("OrderDate = " & rdr.GetDateTime(2))
Console.WriteLineO
Loop
rdr.CloseO
en,Close()

Visual C# .NET
string strConn, strSQL;

strConn = "Data Source={local)\\NetSDK;Initial Catalog=N o r t h w i n d ; " +


"Trusted_Connection=Yes;";
StrSQL = "SELECT OrderlD, CustomerlD, OrderDate FROM Or ders " +
"WHERE CustomerlD = @CustomerID";
SqlConnection en = new SqlConnection(strConn);
SqICommand end = new SqlCommandCstrSQL, en);
SqlParameter param;
param = cmd.Parameters.Add{"@CustomerID", SqlD bType.NChar, 5);
param.Value = "ALFKI";
cn.0pen();
SqIDataReader rdr = cmd. ExecuteReaderO;
while (rdr.ReadO)
<
Console.WriteLinef'OrderlD = " + rdr.Get!nt32(0));
Console.WriteLine("CustomerID = " + rdr.GetString(l));

564

Console. WriteLine("OrderDate = " + rdr.GetDateTime(2));


Console.WriteLineO;

I
rdr.Closef);
cn.Close();

Command Table
CommandType.
12, SqlCommand
ExecuteXmlReader. , FOR XML XmlReader,

GetSqkTnnfiaHHbix> SqlTypes
QleDbDataType, SqlDataReader 1<>1
.NET. , SqlDataReader
,
System JDataSqlTypes.
Orders
, SqlTypes Sqllnt32. SqlString SqlDateTime-.
Visual Basic .NET
'Imports System.Data.SqlTypes
Dim strConn, strSQL As String
strConn = "Data Source=(local)\NetSDK; Initial Catalog=No rthwind;" &
"Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, CustomerlD, OrderDate FROM Or ders " & _
"WHERE OrderlD = 10643"
Dim en As New SqlConnection(strConn)
Dim cmd As New SqlCommand(strSQL, en)
Dim rdr As SqlDataReader
Dim intOrderlD As Sqllnt32
Dim strCustomerlD As SqlString
Dim datOrderOate As SqlDateTime
cn.OpenO
rdr = cmd.ExecuteReader(CommandBehavior,Single Row)
If rdr.Read Then
intOrderlD = rdr.GetSqlInt32(0)
StrCustomerlD = rdr.GetSqlString(l)
datOrcterDate = rdr.GetSqlDateTime(2)
End If
rdr.Close()
cn.Close()

.NET

565

Visual C# .NET
//using System.Data.SqlTypes;
string strConn, strSQL;
strConn = "Data Source=(local)\\NetSDK;Initial Catalog=N orthwind;" +
"Trusted_Connection=Yes;";
strSQL = "SELECT OrderlD, CustomerlD, OrderDate FROM Or ders " +
"WHERE OrderlD = 10643";
SqlConnection en = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommandfstrSQL, en);
SqlDataReader rdr;
Sqllnt32 intOrderlD;
SqlStrlng strCustomerlD;
SqlDateTime datOrderDate;
cn.0pen();
rdr = cmd.ExecuteReader(CommandBehavior.Single Row);
if (rdr.ReadO)
{
intOrderlD = rdr.GetSqlInt32(0);
strCustomerlD = rdr,GetSqlString(1);
datOrderDate = rdr.GetSqlDateTime(2);

}
rdr.CloseO;
cn.CloseO;

? .
. SqlTypes , SQL Client .NET Data Provider. .NET, Getlnt32, GetString .., SQL Client .NET Data Provider . . ,
SqlTypes 1015% ,
.NET,
. NULL. ,
.NET, NULL.
NULL, .
.NET NULL. , DataReaderJsDBBull
.
NULL. SqlTypes IsNulL , , .
, .
SqlTypes SqlDataReader -

566

, . . . , SqlDataReader ,


SqlCommand SQL Sewer MSDE.
CommandType, . CommandText SqlCommand
, CommandType StoredProcedure
:
Visual Basic .NET
Dim strConn As String
strConn = "Data Source=(local)\NetSDK; Initial CataLog=No rthwind;" 4
"Trusted_Connection=Yes;"
Dim en As New SqlConnection(strConn)
Dim cmd As New SqlCommand("CustOrdersQrders", en)
cmd.CommandType = CommandType.StoredProcedure
Dim param As SqlParameter
param = cmd.Parameters.Add("@CustomerID", SqlD bType.NChar, 5)
param.Value = "ALFKI"
cn.0pen()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
Do While rdr.ReadO
Console.WriteLine(rdr("QrderID"))
Loop
rdr.Close()
cn.Close()

Visual C# .NET
string strConn;
strConn = "Data Source=(local)\\NetSDK; Initial Catalog=N orthwind;" +
"Trusted_Connection=Yes;";
SqlConnection en = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommandC'CustOrdersOrd ers", en);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param;
param = cmd.Parameters.Add("@CustomerID", SqlD bType.NChar, 5);
param.Value = "ALFKI";
cn.OpenQ;
SqlDataReader rdr = cmd. ExecuteReaderQ;
while (rdr.ReadO)
Console.WriteLine(rdr["OrderID"]);
rdr.CloseO;
cn.CloseO;

SQL Server, , SQL Client .NET Data Provider


:

.NET

567

EXEC CustOrdersOrders @CustomerID


, CommandType no
Text.
, OUT;
EXEC , @ OUT


OleDbConnection GetOleDbScbemaTable,
, . SQL Client .NET Data Provider .
SQL Server .
SQL Server:
SELECT * FROM INFORMATION.SCHEMA.TABLES

, , , .. .
, .
:
SELECT TABLE_NAME FROH INFORMATION_SCHEMA.TABLES
WHERE TABLE.TYPE = 'BASE TABLE 1

:
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE.TYPE = 'VIEW

:
SELECT TABLE.NAME,

COLUMN_NAHE,

DATA_TYPE,

CHARACTER_MAXIMUM_LENGTH,

NUMERIC_PRECISrON, NUMERIC_SCALE
FROH INFORMATION.SCHEMA.COLUMNS
WHERE TABLE_NAME IN (SELECT TABLE.NAME FROM INFORMATION.SCHEMA.TABLES
WHERE TABLE.TYPE

= 'BASE T A B L E 1 )

ORDER BY TABLE.NAME

:
SELECT SPECIFIC.NAME FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE.TYPE = 'PROCEDURE'

:
SELECT SPECIFIC.NAME,

PARAMETER.NAME,

CHARACTER_MAXIHUM_LENGTH,

PARAMETER_MODE,

NUMERIC_PRECISION,

DATAJTYPE,

NUMERIC_SCALE

FROH INFORMATION_SCHEMA.PARAMETERS
WHERE SPECIFIC.NAME IN (SELECT SPECIFIC_NAME
FROM INFORMATION SCHEMA.ROUTINES

568

WHERE ROUTINE. TYPE =


ORDER

BY

'PROCEDURE')

SPECIFIC NAME

SQL
Server Books Online.

ODBC .NET Data Provider


.NET Framework Microsoft
.NET ODBC .NET Data Provider. , ODBC-.
ODBC .NET Data Provider
.NET Framework, Visual Studio .NET . Web- MSDN ODBC .NET Data Provider, Add Reference (. -1).

NET

[COM | Projects
Version

.NET Co,,.
.NETRu,,.
Mterpsoft.DaU.Qcbc.dl
d
Microsoft. Cat d,5qlXm
Microsoft JScript
Microsoft .msht ml
Microsoft, stdformar.
Mcrosoft. VisualBasi , V,.sa,
Microsoft.VisualC
Microsoft, VisualStudio,.vccod...
VCCod
.VCProiect
Microsoft.Visu.
Mirrrnnfr Umi,
.WPrm...

7.0.3300.0
7,0.3300,0
I.Q.3300.G
3,0.1523,0
7,0.3300,0
' I

..IV

7,0.3300,0
7,0.3300.0
7,0.3300,0
7,0.3300.0
7,0.3300,0
7..^

Tpa

~~~~

T*l

O:\WIhlrJHMicrosoft, NEHFra...
D:I.WINNHMicroEoFt.NET\Fra.,,
O:\Pfogr am Rte^MfcrQSOft.tJ.,.
D;\ProgramFile5l.SQLXML3,0...
D : \WINNT\Micro5oft ,NET\Frd. , ,
D:\ProgfamFile5y4iciasoft.N,..
DilProgiam Files \\ soft. N...
D;\WlNNT\Microsoft.NET\Fra...
D:lW,INNTlMiCtOSOrt.NET\F[a...
D : ^S,NETiCommon7\roE\Pu. . .
D : \VS.NET\Common7UoriPu. . ,
' \V1.NFTlrnrnmnn7lrnFlfti... \

eeted Components:
c soft .oats iOdbt.dl

Cancel

. -1.

ODBC .NET Data Provider

. -1 , ODBC .NET Data Provider


OLE DB SQL Client .NET Data
Provider. ODBC .NET Data Provider,
, MicrosoftData.Qdbc. ,
, .NET Framework, .
SystemData.Odbc.
,
( Import Visual
Basic .NET using Visual * .NET)
ODBC .NET Data Provider.

.NET

569

OdbcConnection
ODBC .NET Data Provider OdbcConnection. OdbcConnection, ConnectionString ( ) OdbcConnection.Open.

OdbcConnection. , ConnectionString OdbcConnection,
ODBC-.
SQL Server :
Driver={SQL Server};Server=(local)\NetSDK;
Database=Northwind; 1=;=;
SQL Server :
Driver={SQL Serve };Server=(local)\NetSDK;
Database=Northwind;Trusted_Connection=Yes;
SQL Server DSN- ODBC ODBC:
05=1;
SQL Server DSN- ODBC:
=;
MSDE, .NET Framework SDK:
Visual Basic .NET
Dim strConn As String
strConn = "Driver={SQL Server};Server=(local)\NetSDK;" &
"Database=Northwind;Trusted_Connection=Yes;"
Dim en As New OdbcConnection(strConn)
cn.OpenO
cn.CloseO
Visual C# .NET
string strConn;
strConn = "Driver={SQL Server};Server=(local)\\NetSDK;" +
"Database=Northwtnd;Trusted_Connection=Yes;";
OdbcConnection en = new OdbcConnection(strConn );
cn.OpenO;
cn.CloseO;


ODBC .NET Data Provider
, OLE DB .NET Data Provider. ? Parameters

570

OdbcCommand OdbcParameter.
ODBC .NET Data Provider .

OdbcDataAdapter
DataSet DataTahle OdbcDataAdapter:
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Driver=(SQL Server};Server=(local)\NetSDK;" & _
"Database=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, CustomerlD, OrderDate FROM Or ders " &
"WHERE CustomerlD = ?"
Dim da As New OdbcDataAdapter(strSQL, strConn}
Dim param As OdbcParameter
param = da.SelectCommand.Parameters.Add("@Cust omerlD", OdbcType.NChar, 5)
param.Value = "ALFKI"
Dim tbl As New DataTableC'Orders")
da.Fill(tbl)

Visual C# .NET
string strConn, strSQL;
strConn = "Driver={SQL Server};Server=(local)\\NetSDK;" +
"Database=Northwind;Trusted_Connection=Yes;";
StrSQL = "SELECT OrderlD, CustomerlD, OrderDate FROM Or ders " +
"WHERE CustomerlD = ?";
OdbcDataAdapter da = new OdbcDataAdapter(strSQ L, strConn);
OdbcParameter param;
param = da.SelectCommand.Parameters.Add{"@Cust omerlD", OdbcType.NChar, 5);
param.Value = "ALFKI*;
DataTable tbl = new DataTableC'Orders");
da.Fill(tbl);


OdbcDataReader
, OdbcCommand OdbcDataReader.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Driver={SQL Server};Server=(local)\NetSDK;" &
"Database=Northwind;Trusted_Connection=Yes;"
strSQL = "SELECT OrderlD, CustomerlD, OrderDate FROM Or ders " & _
"WHERE CustomerlD = ?"
Dim en As New OdbcConnection(strConn)

.NET

571

Dim cmd As New OdbcCommancKstrSQL, en)


Dim param As OdocParameter
param = cmd.Parameters.Add("@CustomerID", Odbc Type.NChar, 5)
param.Value = "ALFKI"
cn.OpenO
Dim rdr As OdbcPataReader = cmd.ExecuteReader( )
Do While rdr.ReadO
Console.WriteLine("OrderID = " & rdr.Get!nt32(0))
Console.WriteLineC'CustomerlD = " & rdr.GetString(1
Console.WriteLine("OrderDate = " & rdr.GetDateTime(2))
Console.WriteLine()
Loop
rdr.Close()
cn.CloseO
Visual C# .NET
string strConn, strSQL;
strConn = "Driver=(SQL Server};Server=(local)\\NetSDK;" +
"Database=Northwind;Trusted_Connection=Yes;";
strSQL = "SELECT OrderlD, CustomerlD, OrderDate FROM Or ders " +
"WHERE CustomerlD = ?";
OdbcConnection en = new OdbcConnection(strConn );
DdbcCommand cmd = new OdbcCommand(strSQL, on);
OdbcParameter param;
param = cmd.Parameters.Add("@CustomerID", Odbc Type.NChar, 5);
param.Value = "ALFKI";
cn.OpenO;
OdbcDataReader rdr = crod.ExecuteReaderO;
while (rdr.ReadO)
(
Console.WriteLine("QrderID = " + rdr.GetInt32(0)>;
Console.WriteLineC'CustomerlD = " + rdr.GetString(1;
Console.WriteLine("OrderDate = " + rdr.GetDateTime(2));
Console.WriteLinef);

!
rdr.Closef);
en.Closef);


ODBC .NET Data Provider OdbcCommand
Table StoredProcedure CommandType.
ODBC .NET Data Provider
CALL ODBC. , :
{? = CALL MyStoredProc(?, ?, ?)}
O\LL.
,
( , -) ?. -

572

, . ?=, , ,
. .
ODBC .NET Data Provider:
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Driver={SQL Server};Server={local)\NetSDK;" &
"Database=Northwind;Trusted_Connection=Yes;"
strSQL = "{CALL CustOrdersOrdersC?)}"
Dim en As New OdbcConnection(strConn)
Dim cmd As New OdbcCommand(strSQL, en)
Dim pa ram As OdbeParameter
param = cmd. Parameters.Add("@CiJStomerID", Odbc Type.NChar, 5)
param.Value = "ALFKI"
cn.OpenO
Dim rdr As OdbcDataReader = cmd,ExecuteReader( )
Do While rdr.ReadO
Console.WriteLineC'OrderlD = " & rdr.Get!nt32(0))
Console.WriteLine("OrderDate = " & rdr.GetDateTime(l))
Console. WriteLineO
Loop
rdr.CloseO
cn.Close()

Visual C# .NET
string strConn, strSQL;
strConn = "Driver={SQL Server};Server=(local)\\NetSDK;" +
"Database=Northwind;Trusted_Connection=Yes;";
strSQL = "{CALL CustOrdersOrdersC?)}";
OdbcConnection en = new OdbcConnection(strConn };
OdbcCommand cmd = new OdbcCommand(strSQL, en);
OdbcParameter param;
param = cmd.Parameters.Add("@CustomerID", Odbc Type.NChar, 5);
param.Value = "ALFKI";
cn.OpenO;
OdbcDataReader rdr = cmd.ExecuteReaderO;
while (rdr.ReadO)
-,
Console.WriteLine("OrderID = " + rdr.Get!nt32(0));
Console.WriteLineC'QrderDate = " + rdr.GetDateTime(l));
Console.WriteLineO;
)
rdr.CloseO;
cn.CloseO;

.NET

573


, ODBC .NET Data Provider, no
, . QleDhConnection.GetOleDbSchema. SQL Server MSDE , -
, ,
SQL Client .NET Data Provider, , . ,
,


Oracle Client .NET Data Provider
Microsoft .NET Oracle. Oracle 8i Oracle,
, LOB BFILE. ,
REF .
Microsoft , Oracle Client .NET
Data Provider .NET Framework. , , , ODBC .NET Data Provider. Oracle Client .NET Data Provider MicrosoftData.OracteCHent.
, Oracle Client .NET Data Provider
Oracle Oracle. Oracle Oracle Client .NET Data Provider
Oracle 8.1.7 .
, , ,
Oracle .
, ( Import Visual Basic
.NET using Visual * .NET) Oracle Client .NET Data Provider.

OracleConnection
Oracle OracleConnection.
.NET, OracleConnection, ConnectionString ( ) OracleConnection.Open.
Visual Basic .NET
Dim strConn As String
strConn = "Data Source=MyOracleDatabaseAlias;" & _
"User ID=MyUserID;Password=MyPasswor d;"

574

Dim en As New OracleConnection(strConn)


cn.Openf)
cn.Close()

Visual C# .NET
string strConn;
strConn = "Data Source=MyOracleDatabaseAlias;" +
"User ID=MyUserID;Password=MyPasswor d;";
OracleConnection en = new OracleConnection(str Conn);
cn.OpenO;
cn.CloseO;


SQL Client .NET Data Provider, Oracle Client .NET Data Provider
. ,
, . . Oracle :
SELECT EMPNO,

ENAME FROM EHP WHERE JOB = ;JOB


OracleDataAdapter
OracleDataAdapter
DataTable .

Visual Basic .NET


Dim strConn, strSQL As String
strConn = "Data Source=MyOracleDatabaseAlias;" & _
"User ID=HyUserID;Password=MyPasswor d;"
StrSQL = "SELECT EMPNO, ENAME FROM EHP WHERE JOB = :JOB "
Dim da As New OracleDataAdapter(strSQL, strCon n)
Dim param As OracleParameter
param = da.SelectCommand.Parameters.Add(":JOB" , OracleType.VarChar, 9)
param.Value = "CLERK"
Dim tbl As New DataTable()
da.Fill(tbl)
Console.WriteLine("Retrieved " & tbl.Rows.Count & " row(s)")

Visual C# .NET
string strConn, strSQL;
strConn = "Data Source=MyOracleDatabaseAlias;" +
"User ID=MyUserID;Password=MyPasswor d;";
StrSQL = "SELECT EMPNO, ENAHE FROM EMP WHERE JOB = :JOB ";
OracleDataAdapter da = new OracleDataA6apter(s trSQL, strConn);
OracleParameter param;
param = da.SeLectCommand.Parameters.Addf";JOB" , OracleType.VarChar, 9);

.NET

575

param.Value = "CLERK";
DataTable tbl = new DataTableO;
da.Fill(tbl);
Console.WriteLine("Retrieved " + tbl.Rows.Count + " row(s}");


OracleDataReader

OracleDataReader.
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Data Source=MyOracleDatabaseAlias;" &
"User ID=MyUserID;Password=HyPasswor d ; "
strSQL = "SELECT EHPNO, ENAME FROM EHP WHERE JOB = :JOB "
Dim en As New OracleConnection(strConn)
Dim cmd As New OracleCommandCstrSQL, en)
Dim param As OracleParameter
param = cmd.Parameters.Add(":JOB", OracleType. VarChar, 9)
param.Value = "CLERK"
cn.Openf)
Dim rdr As OracleDataReader = cmd.Executefleade r()
Do While rdr.ReadO
Console.WriteLine("EmpNo = " & rdr.GetDecimal(Q))
Console.WriteLineC'EName = " & rdr.GetString(l))
Console.WritelineO
Loop
rdr.Close{)
cn.CloseO

Visual C# .NET
string strConn, strSQL;
strConn = "Data Source=MyOracleDatabaseAHas;" +
"User ID=MyUserID;Password=MyPasswor d;";
strSQL = "SELECT EMPNO, ENAME FROM EMP WHERE JOB = :JOB ";
OracleConnection en = new OracleConnection(str Conn);
OracleCommand cmd = new OracleCommand(strSQL, en);
OracleParameter param;
param = cmd.Parameters.Add(":JOB", OracleType. VarChar, 9);
param.Value = "CLERK";
cn.OpenO;
OracleOataReader rdr = cmd.ExecuteReader();
while (rdr.ReadO)
{
Console.WriteLineC'EmpNo = " + rdr.GetDecimal(O));
Console.WriteLineC'EName = " + rdr.GetString{1;
Console.WriteLineO;

576

rdr.Close();
cn.CloseO;

Oracle
Oracle Client .NET Data Provider Oracle
, , SQL Client .NET Data Provider SQL Server. DataReader, NULL.
, , .NET.
Oracle .

Visual Basic .NET


Dim strConn, strSQL As String
strConn = "Data Source=HyOracleDatabaseAlias;" & _
"User ID=MyUserID;Password=MyPasswor d;"
StrSQL = "SELECT EMPNO, ENAME FROM EMP WHERE JOB = :JOB "
Dim en As New OracleConnection(strConn)
Dim cmd As New OracleCommand(strSQL, en)
Dim param As OracleParameter
param = cmd.Parameters.Add(": JOB", QracleType. VarChar, 9)
param.Value = "CLERK"
Dim numEmpNo As OracleNumber
Dim strEName As OracleString
cn.QpenO
Dim rdr As OracleDataReader = cmd.ExecuteReade r()
Do While rdr.Read()
numEmpNo = rdr.GetOracleNumber(O)
strEName = rdr.GetOracleString(l)
Console.WriteLineC'EmpNo = " & numEmpNo.ToStringO)
Console.WriteLlne("EName = " & strEName.ToStringO}
Console. WriteLineO
Loop
rdr.Close()
cn.CloseO

Visual C# .NET
string strConn, strSQL;
strConn = "Data Source=MyOracleDatabaseAlias;" +
"User ID=MyUserID;Password=MyPasswor d;";
StrSQL = "SELECT EMPNO, ENAME FROM EMP WHERE JOB = :JOB ";
OracleConnection en = new QracleConnection(str Conn);
OraclaCommand cmd = new OracleCommand(strSQL, en);
OracleParameter param;

.NET

param = cmd.Parameters.Add(":JOB", QracleType. VarChar,


param,Value = "CLERK";

577

9);

QracleNumber numEmpNo;
OracleString strEName;
cn.OpenO;
OracleDataReader rdr = cmd.ExecuteReaderC);
while (rdr.ReadO)

(
numEmpNo = rdr.GetOracleNumber(O);
strEName = rdr.GetOracleString(l);
Console.WrlteLineC'EmpNo = " + numEmpNo. ToStringO);
Console.WriteLine("EName = " + strEName. ToStringO);
Console.WriteLine();

}
rdr.CloseO;
cn,Close();


CommandText OracleCommand
Parameters Command.
, . ExecuteNonQuery-,
Visual Basic .NET
Dim strConn As String
strConn = "Data Source=MyOracleDatabaseAlias;" &
"User ID=MyUserID;Password=MyPasswor d;"
Dim en As New OracleConnection(strConn)
Dim cmd As New OracleCommand("GetNumOrders", n)
cmd.CommandType = CommandType.StoredProcedure
Dim param As OracleParameter
param = cmd.Parameters.AddC'pCustomerlD", Orac leType.Char, 5)
param.Value = "ALFKI"
param = cmd.Parameters.AddC'pNumOrders", Oracl eType.Int32)
param,Direction = ParameterDirection. Output
cn.OpenO
cmd.ExecuteNonQuery()
Console.WriteLine(pa ram.Value)
cn.CloseO

Visual C# .NET
string strConn;
strConn = "Data Source=MyOracleDatabaseAlias;"
"User ID=MyUserID;Password=MyPasswor
OracleConnection en = new OracleConnection(str
OracleCommand cmd = new OracleCommandC'GetNumO
cmd.CommandType = CommandType.StoredProcedure;
OracleParameter param;

+
d;";
Conn);
rders", en);

578

param = cmd.Parameters.AddC'pCustomerlD",

Orac leType.Char,

5);

param.Value = "ALFKI";

param = cmd.Parameters.Add("pNumOrders", Oracl eType.Int32);


param.Direction = ParameterDirection.Output;
cn.0pen();
cmd. ExecuteNonQueryO;
Console.WriteLine(param. Value);
en.Closet);
Oracle, Command-Type
, Text, CommandText :
BEGIN GetNumOrders(;pCustomerID, :pNumdrders);

END;

REF
Oracle Client .NET Data Provider REF. ,
Oracle:
CREATE PACKAGE PackCursorTest AS
TYPE curOrders IS REF CURSOR RETURN OrdersKR OWTYPE;
TYPE curDetails IS REF CURSOR RETURN Order.D etailsXROWTYPE;
PROCEDURE
OrdersAndDetailsForCustomer
(pCustomerlD IN CHAR, pQrders OUT curOrder s, pDetails OUT curDetails);
END;
CREATE PACKAGE BODY PackCursorTest AS
PROCEDURE OrdersAndDetailsForCustomer

(
pCustomerlD IN CHAR,
pOrders OUT curOrders,
pDetails OUT curDetails

)
AS
BEGIN
OPEN pOrders FOR SELECT * FROM Orders WHER E CustomerlD = pCustomerlD;
OPEN pDetails FOR SELECT * FROM Order.Deta Us WHERE OrderlD IN
(SELECT OrderlD FROM Orders WHERE Custom erID = pCustomerlD);
END;
END;

REF DataSet:
Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Data Source=MyOracleDatabaseAlias;" 4
"User ID=HyUserID;Password=MyPasswor d;"
Dim en As New OracleConnection(strConn)

.NET

strSQL = "PackCursorTest.OrdersAndDetailsForCustomer"
Dim cmd As New OracleCommand(strSQL, en)
cmd-CommandType = CommandType.StoredProcedure
Dim param As OracleParameter
param = cmd,Parameters.Add("pCustomerID", Orac leType.Char, 5)
param.Value = "ALFKI"

param = cmd.Parameters.AddC'pOrders", OracleTy pe.Cursor)


param.Direction = ParameterDirection.Output
param = cmd.Parameters.Add("pDetails", Oracle! ype.Cursor)
param,Direction = ParameterDirection.Output
Dim da As New OracleDataAdapter(cmd)
da.TableMappings.Add("Table", "Orders")
da.TableMappings.Add("Table1", "Order_Details")
Dim ds As New DataSetf)
Dim tbl As DataTabLe

da.Fill(ds)
For Each tbl In ds,Tables
Console.WriteLine(tbl.TableName & " now has " &
tbl.Rows.Count & " row(s)")
Next tbl
Visual C# .NET
string strConn, strSOL;
strConn = "Data Source=MyOracleDatabaseAlias;" +
"User ID=MyUserID;Password=MyPasswor d ; " ;
OracleConnection en = new OracleConnection(str Conn);
strSQL = "PackCursorTest.OrdersAndDetailsForCustomer";
OracleCommand cmd = new OracleCommand(strSQL, en);
cnid.ComniandType = CommandType.StoredProcedure;
OracleParameter param;
param = cmd.Parameters.Add("pCustomerIO", Orac leType.Char, 5):
param.Value = "ALFKI";
param = cmd.Parameters.AddC'pOrders", OracleTy pe.Cursor);
param.Direction = ParameterDirection.Output;
param = cmd.Parameters.AddC'pDetails", OracleT ype.Cursor);
pa ram.Direction = ParameterDirection.Output;
OracleDataAdapter da = new OracleDataAdapterfc md);
da.TableMappings.Add("Table", "Orders");
da.TableMappings.Add("Tablel", "Order_Details");
DataSet ds = new DataSetO;
da.Fill(ds);
foreach (DataTable tbl in ds.Tables)
Console,WriteLine(tbl.TableName + " now has " +
tbl.Rows.Count + " row(s)");

579

580


Oracle Client .NET Data Provider , , Oracle.
Oracle . , :
SELECT TABLE_NAME FROM USER.TABLES
SELECT TABLE_NAHE, COLUMN_NAME FROM USER_TAB_COLUHNS
ORDER BY TABLE_NAME

Oracle
Oracle.

, .NET
.NET ,
,
. .NET
.

,
, , SQL Client .NET
Data Provider. , ,
SQL Server, Oracle. SQL Client .NET Data Provider, .
,
DataSet, DataTable, IDataReader
DbDataAdapter, .
, .
, SQL Client .NET Data
Provider, DataTable.
, , .
, , DataAdapter {DbDataAdapter.
GetQrdersForCustomer, CustomerlD DataTable . SqlDataAdapter.
Visual Basic .NET
Dim strCustomerlD As String = "ALFKI"
Dim tblOrders As DataTable
tblOrders = GetOrdersForCustomer(strCustomerID )

.NET

581

Private Function GetOrdersForCustomer(Customer ID As String) As DataTable


Dim strSQL, strConn As String
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, Order Date " & _
"FROM Orders WHERE CustomerlD = CustomerlD"
strConn = "Data Source=(local)\NetSDK;" &
"Initial Catalog=Northwind;Trusted_Connection= Yes;"
Dim da As New SqlDataAdapter(strSQL, strCo nn)
Dim param As SqlParameter
param = da.SelectCommand.Parameters.Add("@ CustomerlD", SqlDbType.NChar, 5}
param,Value = CustomerlD
Dim tbl As New DataTable("Orders")

da.Fill(tbl)
Return tbl
End Function
Visual C# .NET
string strCustomerlD = "ALFKI";
DataTable tblOrders;
tblOrders = GetOrdersForCustomer(strCustoirerID );
private DataTable GetOrdersForCustomer(string
CustomerlD)
{
string strSQL, strConn;
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, Order Date " +
"FROM Orders WHERE CustomerlD = @CustomerID";
strConn = "Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection= Yes;";
SqlDataAdapter da = new SqlDataAdapter(str SQL, strConn);
SqlParameter pa'ram;
param = da.SelectCommand.Parameters.Add("@ CustomerlD", SqlDbType.NChar, 5);
param.Value = CustomerlD;
DataTable tbl = new DataTable("Orders");

da.Fill(tbl);
return

tbl;

,
. GetOrdersForCustomer
SQL Client .NET Data Provider, string DataTable.
, .NET, DataTable. GetOrdersForCustomer, .
Visual Basic .NET
Private Function GetOrdersForCustomer(Customer ID As String) As DataTable
Dim strSQL, strConn As String
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, Order Date " & _
"FROM Orders WHERE CustomerlD = :CustomerID"

582

strConn = "Data Source=MyOracleDatabaseAlias;" 4 _


"User ID=MyUserID;Password=MyPassword;"
Dim da As New OracleDataAdapter(strSQL, st rConn)
Dim param As OracleParameter
param = da.SelectCommand.Parameters.Add(": CustomerlD", OracleType.Char, 5)
param.Value = CustomerlD
Dim tbl As New DataTable("Orders")
da.FillCtbl)
Return tbl
End Function
Visual C# .NET
private DataTable GetOrdersForCustomer(string

CustomerlD)

!
string strSQL, strConn;
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, Order Date " +
"FROM Orders WHERE CustomerlD = :CustomerlD";
strConn = "Data Source=MyOracleDatabaseAHas;" +
"User ID=MyUserID;Password=MyPassword;";
OracleDataAdapter da = new OracleDataAdapt er{strSQL, strConn);
OracleParameter param;
param = da.SelectCommand.Parameters.Add(": CustomerlD", OracleType.Char, 5);
param.Value = CustomerlD;
DataTable tbl = new DataTableC"Orders");
da.FillCtbl);
return tbl;
I

,
, .NET. , , SqlDataAdapter IDbDataAdapter.
Visual Basic .NET
Dim daOrders As IDbDataAdapter = GetOrdersAdap ter()
Dim strCustomerlD As String = "ALFKI"
Dim param As IDbDataParameter
param = CType(daOrders.SelectCommand. Parameter s{0), IDbDataParameter)
param.Value = StrCustomerlD
Dim ds As New DataSetQ
Dim tblOrders As DataTable = ds.Tables.AddC'Or ders")
daOrders,Fill(ds)
Private Function GetOrdersAdapterO As IDbData Adapter
Dim strSQL, strConn As String
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, Order Date " & _
"FROM Orders WHERE CustomerlD = CustomerlD"
strConn = "Data Source=(local)\NetSDK;" &

.NET

583

"Initial Catalog=Northwind;Trusted_Connection= Yes;"


Dim da As New SqlDataAdapter(strSQL, strCo nn)
da.TableMappings.Add("Table", "Orders")
da.SelectCommand.Parameters.Add{"@Customer ID", SqlDbType.NChar, 5)
Return da
End Function

Visual C# .NET
IDbDataAdapter daOrders = GetOrdersAdapterf);
string strCustomerlD = "ALFKI";
IDbDataPararneter param;
param = (IDbDataParameter) daOrders.SelectComm and.Parameters[0];
param.Value = strCustomerlD;
DataSet ds = new DataSetO;
DataTable tblOrders = ds.Tables.Add("0rders");
daOrders,Fill(ds);

private IDbDataAdapter GetOrdersAdapterQ


I
string strSQL, strConn;
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, Order Date " +
"FROM Orders WHERE CustomerlD = @CustomerID";
strConn = "Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection= Yes;";
SqlDataAdapter da = new SqlDataAdapter(str SQL, strConn);
da.TableMappings.Add{"Table", "Orders");
da.SelectCommand.Parameters.Add("Customer ID", SqlDbType.NChar, 5);
return da;
:
GetQrdersAdapter , ,
OradeDataAdapter
IDbDataAdapter. , IDbDataAdapter, .
Visual Basic .NET
Private Function GetOrdersAdapterC) As IDbData Adapter
Dim strSQL, strConn As String
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, Order Date " &
"FROM Orders WHERE CustomerlD = :CustomerID"
strConn = "Data Source=MyOracleDatabaseAlias;" 4
"User ID=MyUserID;Password=MyPassword;"
Dim da As New QracleDataAdapter(strSQL, st rConn)
da.TableMappings.Add("Table", "Orders")
da.SelectCommand.Parameters.Add(":Customer ID", OracleType.Char, 5)
Return da
End Function

584

Visual C# .NET
private

IDbDataAdapter

GetOrdersAdapter()

{
string strSQL, strConn;
strSQL = "SELECT OrderlD, CustomerlD, EmployeelD, Order Date " +
"FROM Orders WHERE CustomerlD = :CustomerID";
strConn = "Data Source=HyOracleOatabaseAlias; " +
"User ID=MyUserID; Password=HyPassword; ";
OracleDataAdapter da = new OracleDataAdapt er(strSQL, strConn);
da. TableMappings.Addf "Table", "Orders");
da . SelectCommand . Pa ramete rs . Add( " : Custome r ID" , 0 racleType . Char, 5) ;
return da;

.NET
.NET, , . ,
.NET ,
, .
ODBC .NET Data Provider, , ADO.NET:
? , DataAdapter. , UpdateCommand
DataAdapter :
UPDATE Orders SET CustomerlD = ?, OrderDate =
WHERE OrderlD = ?

QrderDate?
, ,
. . SQL Server Northwind ODBC .NET Data
Provider, OdbcType QdbcParameter QdbcTypeDateTime, OLE DB .NET Data Provider
OleDbType OleDbParameter OleDbTypeDBTimeStamp. ?
, , GetScbemaTableDataReader. . , . Command
ExecuteReader. GetScbemaTable DataReader. DataTable, DataReader.GetScbemaTable,
. DataTable , . ProviderType .

.NET

585

OdbcType OrderDate Northwind.


Visual Basic .NET
Dim strConn, strSQL As String
strConn = "Driver={SQL Server};Server=(local)\NetSDK;" &
"Database=Northwlnd;Trijsted_Connection=Yes;"
Dim en As New OdbcConnection(strConn)
cn.OpenO
strSQL = "SELECT OrderDate FROM Orders"
Dim cmd As New OdbcCommand(strSQL, en)
Dim rdr As OdbcDataReader
rdr = cmd.ExecuteReader(CommandBehavior.Schema Only)
Dim tbl As DataTable = rdr.GetSchemaTableO
rdr.CloseQ
cn.Close()
Dim intOrderDateType As Integer
intOrderDateType = CType(tbl.Rows(0)("Provider Type"), Integer)
Dim odbcOrderDateType As OdbcType
odbcOrderDateType = CType(intOrderDateType, Od bcType)
Console.WriteLine("OrderDate")
Console.WriteLineCvbTab & "ProviderType = " & intOrderDateType)
Console,WriteLinefvbTab & "OdbcType = " & OdbcOrderDateType.ToStringO)
Visual C# .NET
string strConn, strSQL;
strConn = "Driver={SQL Server};Server=(local)\\NetSDK;" +
"Database=Northwind;Trusted_Connection=Yes;";
OdbcConnection en = new OdbcConnection(strConn );
cn.OpenO;
strSQL = "SELECT OrderDate FROM Orders";
OdbcCommand cmd = new OdbcCommand(strSQL, en);
OdbcDataReader rdr = ctnd. ExecuteReader(Comroand Behavior.SchemaOnly);
DataTable tbl = rdr.GetSchemaTable();
rdr.Close();
cn.CloseO;
int intOrderDateType = (int) tbl.Rows[0]["Prov iderType"];
OdbcType odbcOrderDateType * (OdbcType) intOrd erDateType;
Console.WriteLine("OrderDate");
Console.WriteLine("\tProviderType = " + intOrderDateType);
Console. WriteLine( "\tOdbcType = " + odbcOrderDateType.ToStringO);

, Ad Hoc Query
Tool, - ( ). . -2 Ad Hoc Query Tool , .NET . , OrderDate DateTime OdbcType.

20

595

586

. -2. .NET
Ad Hoc Query Tool

- , , ADO.NET Ad Hoc Query- Tool ADO.NET DataAdapter


Builder ADO.NET Navigation Control.
. ,
. Web-,
- Readme.
,
. , -
. Ad Hoc Query Tool DataAdapter Builder Microsoft
Visual Basic .NET Navigation Control Visual Basic
.NET Visual * .NET
: (
Microsoft ). .

ADO.NET Ad Hoc Query Tool



. Visual Studio .NET .
.NET , .
ADO.NET Ad Hoc Query Tool (. -1) .NET .
,

588

. ADO.NET Act Hoc Query Tool



ADO.NET, DataTable ,

,||....

. -1. ADO.NET Ad Hoc Query Tool


.


Connect.
(. -2),
.NET.

Connection String.

jProvider=50LOLEDB.Data Souce=(local]\NetSDK;l

.NET Date Provider; fgfebb

. -2.

Ad Hoc Query Tool

.NET
Ad Hoc Query Tool
, Microsoft .NET Framework OLE
DB .NET Data Provider SQL Client .NET Data Provider. .NET.
.NET, Microsoft .NET Framework,

589

Connection <Add ProviderX , .NET (. -3).


i* Arlrf .NET Data Pnwmter
Re Name
1

Resouice Nam*

radeDienJ

Delimiters
Ptefi*

. -3. .NET Ad Hoc Query Tool


ADO.NET , , -
, Add .NET Data
Provider , -
. Ad Hoc Query Tool .
OLE DB .NET Data Provider ODBC .NET Data Provider
. , Ad Hoc Query Tool .


Ad Hoc Query Tool
. Execute. Results (. 15-4).
DataTable Code ADO.NET, DataTable.


, , Schema
(. -5). Ad Hoc Query Tool
DataReader.GetschemaTable. Extended MetaData ,
Ad Hoc Query Tool CommandExecuteReader
Keylnfo CommandBehavior. ,
, , ,
,
CommandBuilder Data Adapter Configuration Wizard. ,
OLE DB ODBC- , , -:
, . Ad Hoc Query Tool

590

, .
.
. -5 ColumnName,
ColumnSize, DataType .. , Provider Type.
, .

ctena \ DataTaWe Ile


UBloraeilO

ALFM

.ANATR
".". CANTON
"AROLir
;iLAUS
""BIKK
BLCNP
.BOLD
SOUfF
: BDTTM
BSBEv
CiCIL

:E'IT:

CHOPS

sxui
" " CONSH

'

. -4.

lonp.in'Narit
Alre* F Jteikiitn
AniTiuiillo Ernpai
Jrto Hoietw

tcrfacWanio
HanaAndeit

Ans Truiillo
Antonio Morano
i ,,
Thomas Haidy
ChiBtma Beiojund

Elaua SEE Deht.it Hia Moos


ilondc-: :: 1 peie
FiedeiH^ue Citeau
[lunidas pi Mart in Sommei
Bon
Laurence Lebihan
Elizabeth Lincoln
E's B--!-jges
Viclona Ashworth
Ilad^f: IWiidas p Falicio Simpson
Cantig comaicial
Fiancisco Chang
Op-$uey China] Yang Wang
Comaicio M.nano
PedioAfonso
Consohnalcd Holdi Elizabeth Blown
DiKhenblut Dehk Sven Dttheb
DiinnnleEntiei
Janme Labiune

Phone
' 030X107*321
[5] 555-4729
[5] 555-92
(17115557788
21-123465
0621-08460
88601531
(91) EE5 22 62
81 24 45 40
(604) 555-4728
(171)555-1212
(1)135-5555
[61 555-3332
0452-076515
(11)555-76^
(171) 555-2282
0241-03812:
40 67 88 88

Ad Hoc Query Tool

( AtKI.MIl nil M

lokwiNsme

. -5.

Cdi-fnnlDrdrr

ColuronBize

NumericPreci NumencScale DataType

Picn-ide'ipe 0*0bTjpe

1*UOHS

591

130 202 (. -5) ,


.NET .
OLE DB .NET Data Provider. , , CustomerlD WCbar,
CompanyName VarWChar.
Visual Basic -NET
Dim typCustomerlD, typCompanyName As OleDbType
typCustomerlD = CType(130, OleDbType)
typCompanyName = CType(202, OleDbType)
Console.WriteLineC'CustomerlD is " & typCustomerlD.ToStringO)
Console.WriteLinef"CompanyName is " & typCompanyName.ToStringO)
Visual C# .NET
OleObType typCustomerlD, typCompanyName;
typCustomerlD = (OleDbType} 130;
typCompanyName = (OleDbType} 202;
Console.WriteLineC'CustomerlD is " + typCustomerlD.ToStringO);
Console.WriteLine("CompanyName is " + typCompanyName.ToStringO);

, , , ProviderType ,
Ad Hoc Query Tool , . -5,
GetSchemaTable DataReader. , ,
OleDbType ProviderType;
OleDbType. OleDbType DataTable, GetSchemaTable, Ad
Hoc Query' Tool , , .NET
ProviderType
.
! .NET . SQL XML .NET Data Provider.
, OLE DB .NET SQL Client
.NET.

, .NET, Microsoft OLE DB, SQL Client. ODBC Oracle Client, . , Ad Hoc Query Tool DataAdapter
Builder, .
Reflection . ,
Ad Hoc Query Tool ODBC .NET
Data Provider, , .
, CommandBuilder. DataAdapter Builder -

592

, DataAdapter. , DataAdapter Builder


DataTable, Data.Reader.GetSchemaTable, , , ' .
()
.NET , ,
-, , ,
.NET.


Query Updateable. ,
Ad Hoc Query Tool CommandBuilder,
. , Submit Changes (, -4).
, Ad Hoc Query Tool CommandBuilder
, ,


Ad Hoc Query Tool , .NET, , DataSet
. , Settings . XML-, nanKe\Documents
and Settings\zaffl_wortb3oe#mu8\Application Data\Microsoft ADO.NET\Ad Hoc Query
Tool\, .

ADO.NET DataAdapter Builder


CommandBuilder Data Adapter Configuration Wizard DataAdapter,
. CommandBuilder
, .
Data Adapter Configuration Wizard ,
.NET .NET Framework. ,
, .
ADO.NET DataAdapter
Builder. , OLE DB
ODBC ,
? DataAdapter, .NET Framework? .
ADO.NET DataAdapter Builder
Ad Hoc Query Tool. Connect .
.NET.
DataAdapter Builder ,
. Ad Hoc Query Tool, DataAdapter Builder , .

Jv Stmg

593

ISELECT OrderlD CustomerlD, Employee. GrderDals FFCM Ordeii'-'HE^E CuttomelD

. -.
ADO.NET DataAdapter Builder
, DataAdapter Builder DataAdapter ADO.NET
.


DataAdapter Builder DataAdapter ,
INSERT, UPDATE DELETE.
, DataAdapter Builder UPDATE DELETE, Concurrency Check (. -).
DataAdapter Builder WHERE
. ,

timestamp.
Custom , ,
. -7.
, -.
SET WHERE
DataAdapter . ,
UPDATE DELETE, .
,
.

. -, OLE DB

594

ODBC, . Microsoft V i s u a l FoxPro OLE DB Provider Oracle OLE DB


Provider. CommandBuilder Data Adapter Configuration Wizard ,
UPDATE DELETE . .
OLE DB, ,
DataAdapter
, DataAdapter Builder.
Custom Updating Logic

. -7.

, ,
, ,
time-stamp,
, WHERE UPDATE INSERT
Customers North wind .
.
, . , Order Details,
Products:
SELECT O.OrderlD, 0. ProctuctID, p. ProductName, 0. Quantity, O.UnitPrice
FROM [Order Details] 0, Products P
WHERE P.ProductID = Q.ProductlD AND O.Orde = 10643

10, DataAdapter
R . ,
DataAdapter Builder,
Order Details. Custom Updating Logic , Order Details SET
WHERE ProductName.

595

ADO.NET Navigation Control


13 Windows-
. , , , DataSet , DataAdapter DataSet , . ,
, DataSet, .
ADO.NET Navigation
Control. , DataSet,
, DataSet,
. . -8 ,
ADO.NET Navigation Control.
Fermi

Rowl ol 91
AddHew J_
FHI

Delete
Submit

JJjH
Cancel
Discaid

. -8. ADO.NET Navigation Control Windows-

ADO.NET Navigation
Control Visual Studio .NET
Visual Studio .NET
ADO.NET Navigation Control,
Windows Forms Visual Studio
.NET.
, ADO.NET Navigation Control Visual Studio .NET ,
Customize Toolbox. .NET Framework Components,
Browse Navigation Control. OK,
,

ADO.NET Navigation Control,



Navigation Control Windows-, ,
, : DataSource, DataMember, DataAdapter DataTahle.

596

DataSource DataMember , DataGrid. Navigation Control


, , TextBox DataGrid. DataSource
DataMember Navigation Control CurrencyManager Windows-
.
, Navigation Control Fill
Update. ,
DataAdapter DataTable .


ADO.NET Navigation Control
Navigation Control FillQnload. ConfirmDeletes ShowTips.
FillOnLoadno True. , Navigation Control DataAdapter fill.
ConflrmDeletes True. , Delete
.
, - Navigation Control, . , ShowTips False.

action query . ,
Active Server Pages . ASP
ActiveX Data Objects aw. ADO
ADO (ActiveX Data Objects} 3, 5,
9-14, 18, 20, 47, 61, 86, 134-136,
179, 257, 323
- 7
- 7
- 3,
ADO.NET 2-5, 7, 10, 16, 18, 20, 36, 71,
86, 91, 179, 259
ASP (Active Server Pages) 455
ASP.NET 528
CLR (Common Language Runtime) 4,
53
COM (Component Object Model) 4, 44
COM+ 35
Common Language Runtime CM. CLR
Component Object Model CM. COM
Component Services 446, 452
connected object . ,

conscraint .
cookie 538
DAO (Data Access Objects) 3, 9-14,
18, 134, 136, 179, 257, 323
Data Access Objects CM. DAO
Data Adapter Configuration Wizard
151, 155, 327, 377, 379, 382, 416,
452, 498
Data Definition Language CM. DDL

Data Form Wizard 21, 22, 27, 28, 32,


35, 38, 48, 59, 197
Data Manipulation Language CM. DML
DDL (Data Definition Language) 83
disconnected object . .

DML (Data Manipulation Language) 82


extensible Stylesheet Language
Transformations CM. XSLT
firehose cursor . ,

G
globally unique identifier CM. GUID
GUID (globally unique identifier) 437

Kagera

47

M
managed code .
MDAC (Microsoft Data Access
Components) 8
metadata .
Microsoft Access 8, 22, 6l, 408, 532
Microsoft Data Access Components
CM. MDAC
Microsoft Desktop Engine CM. MSDE
Microsoft Visual InterDev 62
MSDE (Microsoft Desktop Engine) 41,
413,490

0
ODBC 8,46, 47, 55,61, 150
ODBCDirect 3

598

OLE DB 8, 61, 93
Oracle 3, 8, 47, 59, 61, 150, 414
P

Web- 62
Windows Forms 4
Windows- 62, 64

Performance Monitor 53

XDR (XML Data Reduced) 459


XML 3, 7, 16,68, 176, 454
XML Data Reduced CM. XDR
XML Schema Definition CM. XSD
XML Schema Definition Tool 324, 325,
334. 335, 336, 339
XPath 454, 476
XSD (XML Schema Definition) 459
XSLT (extensible Stylesheet Language
Transformations) 16, 454, 478

QBU (query-based updates)


.

Query Builder 102, 153, 155, 157

R
RAD (rapid application development)
136
RDO (Remote Data Objects) 3, 134,
136
RegSvcs.exe 448
Relations Collection Editor 281
Remote Data Objects CM. RDO

s
sequence .
Server Explorer 58, 59, 105, 155
Sn.exe 448
SQL DMO 42
SQL Profiler 41, 53
SQL Server 3, 7, 8, 22, 41, 58; 59, 61.
411
SQL Server Query Analyzer 41, 84
strong name .
transaction .
two-phase commit cm,

V
Visual Basic 3, 62
Visual Basic .NET 22,
Visual Basic 6 3, 36
Visual Studio .NET 2,
100, 102, 151, 211.
Visual Studio 6 3, 48,
Visual Studio 97 3

55, 77
19, 21, 36, 48, 58.
279, 306, 326
61

w
Web Forms 4
Web- 35, 62, 426, 429

192, 410

515
.
RAD


. GUID

446
445, 446

58

3
9
- DDL 83
- DML 82
- , 82, 84
- 91
- 257
- 406
- 10, 95
- 86
- 256, 278
473, 475

- Stream 456, 458


- TextReader 458
- TextWriter 456
- XmlReader 458
- XmlWriter 456
2
- 488
-

- Command 6
- Connection 6
- CurrencyManager 494
- CustomersDataTabte 329
- DataAdapter 134, 140
- DataColumn 13
- DataColumnMappings 138
- DataProvider 6
- DataRow 14, 334
- DataRowCollection 290
- DataSet 16, 36, 324, 328, 502
- DataTable 12, 14
- Decimal 510
- HttpSessionState 541
- OdbcConnection 68
- OleDbConnection 45, 53, 67, 68, 75
- OrdersDataTable 329
- Page 541
- Parameter 6, 122
- SqlConnection 68
- String 293
- Transaction 6
- XmlDataDocument 464
- 62

- 190
- 146, 166, 188, 189,
218, 231,434
- 190

- New 81, 177
- NOCOUNT 418

599

- Nothing 204
- null 204
- SCOPE_IDENTITY

413

- SET NOCOUNT ON 419


- WithEvents 77
62
44
- ConnectionString 45
- DataAdapter 140
- DataRelation 261
- Windows Forms Designer

- 85, 93
- 20

65

2, 11, 12, 18
VIC

- AcceptChanges 224, 225, 232, 233,


244, 245, 355, 410
- Add 119, 190, 200. 510
- AddNew 305, 310, 497
- AddRange 160
- AppendChunk 519
- BeginEdit 202, 209, 244, 245, 305,
316, 332,499
- Beginlnit 224. 226, 232, 233, 310.
311
- BeginLoadDaca 232, 233
- BeginTransaction 10, 55, 70
- Call 145
- Cancel 110
- CancelEdit 15, 209, 244, 245, 305,
316,332
- ChangeDatabase 70, 71
- Clear 206, 224, 226, 232, 233
- ClearErrors 244, 247
- Clone 187, 224, 226, 232, 234
- Close 50, 52-54, 70,72, 75; 112,
115, 117
- Collect 53
- Commit 70, 100
- Compute 232, 234, 235
- Conneccion.Open 6
ContextUtil 449

600

187, 225, 226, 232, 234


310, 311
CreateChildView 316
CreateCommand 54, 55, 70, 72, 81
CreateParameter 110, 120, 476
DataAdapter.Fill 10, 12, 146, 148,
150
- DataBind 536
- Delete 205, 244, 247, 305, 310, 316:
317
- DeriveParameters 396
- Dispose 5355
- EditDetail 506
- EndCurrentEdit 499
- EndEdit 15, 202, 209, 244, 245, 305,
316, 332,499
- Endlnit 225, 226. 233, , 311
- EndLoadData 233
- Eval 533
- ExecuteNonQuery 9, 83, 85, 110,
111, 355,419,420,481
- ExecuteReader 9, 85, 92, 95, 110.
I l l , 112, 375
- ExecuteScalar 93,94,110,113
- ExecuteXmlReader 9, 468
- F i l l 5,31,32,135,141-145,163,
177, 178. 186, 472, 515, 549

- FillSchema 151, 163, 166, 167, 185,


186, 337,416
- Find 184, 289, 290, 291, 303,
312, 331
- FindRows 304, 311, 312
- Get 88
- > 115, 116
- GetBytes 115, 521
- GetChanges 16, 35, 225, 226, 233,
235, 342, 423, 426
- GetChars 115, 521
- GetChildRows 244, 247, 263, 265,
334
- GetChunk 519
- GetColumnError 244, 247
- GetColumnsInError 244, 248
- GetData 114, 115, 119
- GetDatalypeName 115, 118
- GetDeleteCommand
390, 396, 397

GetEnumerator 301, 311, 313


GetErrors 233, 235
GetFieldType 115
GetFillParameters 163, 167
GetlnsertCommand 390, 396, 397
Getlnt32 88
GetName 115, 118
GetOleDbSchemaTable 56, 57, 58,
70, 72, 74
- GetOrdinal 87, 115, 118
- GetParentRow 244, 248, 263, 265,
334
- GetParentRows 244, 248, 264, 265
- GetSchemaTable 112, 115, 118
- GetString 88, 521
- GetUpdateCommaiid 390, 396, 397
- GetValue 115, 116
- GetValues 115, 116
- GecXml 225, 227,455
- GetXmlSchema 225, 227
- HasChanges 225, 227
- HasVersion 245, 249
- ImportRow 233, 235
- InferXmlSchema 225, 227, 458, 459
- IsDBNull 115
- IsNull 205, 245, 249
- Item 181, 265
- Load 464, 469
- LoadDataRow 201, 233, 235
- Merge 16, 36, 225, 227, 342, 428,
431, 433,442
- MoveFirst 179
- MoveLast 179
- MoveNext 179, 313
- MovePrevious 179
- Navigate 458
- NewRow 201, 233, 235
- NextRecordset 90, 91
- NextResult 89,92, 115, 117
- Open 5, 50, 53, 67, 68, 70, 74, 145,
518
- Prepare 110, 113
- Read 86, 89, 115
- ReadXml 225, 227, 335, 456, 458,
459, 468

- ReadXmlSchema 225, 227, 337,


458,459
- Refresh 127, 512
- RefreshSchema 396, 39"
- RejectChanges 225, 233. 245
- ReleaseConnectionPool 53
- ReleaseObjectPool 70, 75
- Remove 206
- RemoveAt 206, 49/
- Replace 293
- Reset 225, 227, 233, 236
- ResetCo'mmandTimeout 110, 114
- ResumeBinding 512
- Rollback 70, 100
- Select 233, 236, 289, 292, 295, 297,
300, 343,421,424
- SetAbort 449, 450
- SetColumnError 245, 247
- SetCompiete 450
- SetParentRow 248
- SuspendBinding 512
- ToString 510
- Update 5, 6, 11, 34, 135, 159, 162,
163, 167, 363, 368, 442, 479, 498,
504
- UpdateBatch 5, 350
- WhteXml 225, 227, 286, 335, 342,
456, 462, 464, 479
- \VriteXmlSchema 212, 225, 227,
324,458

0

82

. CLR

- Application 542, 545


- Binding 510
- Cache 542
- Command 8,9, 10, 11, 35,41, 54,
72, 81,83, 86,92,95, 100, 105,
133-135, 137, 139, 155, 157, 159,
352
- CommandBuilder 346, 374, 375,
416,452

ConflictAdapter 441
Connection 6, 9, 10, 40, 41, 50-52,
54, 55. 62, 63, 68. 78: 81, 140, 144,
145, 518
Constraint 14, 177
ConstraintCollection 190
CurrencyManagcr 494, 497, 499,
506, 510
Customers 328
DataAdapter 5, 9, 10, 11, 32, 34-36.
106, 107, 134-139, 141, 143, 144,
146, 148, 149, 151, 155, 157, 158.
159, 161, 179, 211, 362, 408, 490.
502, 549
Database 9
DataColumn 12, 13, 14, 142, 177,
178, 184, 188,461
DataColumnMappingCollection 147
DataColumnMappingsCollection
138
DataConnection 36
DataGridTableStylc 504
DataReader 9, 20. 81, 85-89, 9 1.
92,95, 1 1 2 , 133, 179, 181, 520
DataRelation 16, 17, 32, 177, 184,
255, 259, 260, 262, 266, 269, 279,
281, 298
DataRow 12, 14-16, 177, 180, 181,
200, 263, 264
DataRowCollection 184, 200
DataRowView 194, 300, 305, 5u6
DataSet 2, 5,6, 11, 15, 16, 18-20,
24, 31, 32, 33-36, 107, 133-135,
137, 143, 145, 146, 148, 174, 182,
183, 197, 211, 279, 324, 329, 337,
455,461,490, 499, 519, 554
DataTable 11-15, 20, 27; 32, 57,
74, 134, 135, 137, 142, 143, 146: 150,
177, 178, 179, 181, 186, 187, 201,
262, 289, 300, 331,461, 515
DataTableMapping 146
DataTableMappingCollection
146,
147, 160
DataTableMappings 147
DataTableMappingsCollection 138
DataTablesColiection 187
DataView 17, 194, 297; 299, 316

602

Field 13
ForeignKeyConstraint 184, 277
HttpCookie 539
lEnumerator 301
InsertCommand 407
OdbcDataAdapter 479
OleDbCommand 55, 97, 101, 105,
106, 110. 159, 468
- OleDbCommandBuilder 395
- OleDbConnection 6, 40, 44, 46, 50,
53, 55, 56, 58, 63-68, 70, 74, 75, 77,
101,471, 490
- OleDbDataAdapter 31, 32, 37, 159,
165, 327, 472,479,490, 502
- OleDbDataReader 114, 115, 537
- OleDbParameter 109, 120, 122, 125
- Orders 328
- Parameter 10,81,95, 119, 157
- ParameterCollection 127
- QueryDef 9. 10, 134
- Recordset 3, 5, 11, 12, 14, 18, 20,
90, 91, 135, 136, 1.62, 179, 258, 349
- Request 538
- Response 538
- Session 542
- SqlCommand 8, 9, 97, 105, 159, 468
- SqIConnection 6, 53, 55, 63, 65
- SqlDataAdapter 159,479
- SqlXmlAdapter 471,472,479
- SqlXmlCommand 471,472,477,
478.479, 481, 484
- SqlXmlParameter 471, 476
- Stream 324
- StreamReacler 85
- TextReader 85
- TextWriter 324
- Transaction 10, 41, 54, 55, 70, 100
- UniqueConstraint 190
- ViewState 545
- XmlDataDocument 464
- XmlDocument 463, 469
- XmlReader 85, 468
- XmlWriter 324
- 4, 5, 6, 11. 12
- 4, 5, 8

- 19,
329
- 85
183, 190
- ForeignKeyConstraint 184, 197,
219, 220, 266, 268, 269, 272, 279
- PrimaryKey 184, 190
- UniqueConstraint 184, 219
- UniqueKey 190, 266, 268
- 266
58

36, 62
383
98

- DataRowVersion 300
- DataViewRowState 297, 300
414
6, 8, 60
- Microsoft Jet 4.0 OLE DB
Provider 47, 67
- Microsoft OLE DB Provider For
ODBC Drivers 61
- Microsoft OLE DB Provider for
Oracle 47, 67, 150
- Microsoft OLE DB Provider for SQL
Server 67
- OLE DB .NET Data Provider 6, 8,
46, 377
- SQL Client .NET Data Provider 6, 7,
8, 377
- SQL Server OLE DB Provider 7
- SQL XML .NET Data Provider 8,
470, 472, 473, 479
- 6
62
5
- Microsoft.Data.SqlXml 470
- System 205
- System.Collections 301
- System.Data 6, 40, 69, 148, 150,
161, 166, 177, 277
- System.Data.OleDb 6, 40
- System.Data.SqlClient 6, 40

- System.EnterpriseServices
50, 518

448

53
5

- AcceptChangesDuringFill 158, 162


- AcceptRejectRule 251, 279
- AllowCustomPaging 547
- AllowDBNull 13, 183, 189, 237, 238
- ADowDeletc 307
- AllowEtlit 307
- AllowNew 307
- AllowPaging 546, 547
- ApplyDefaultSort 307, 308
- Autolncrement 13, 192, 193, 237,
238,416
- AutoIncrementSeed 192, 193, 197,
237, 238,423,490, 502
- AutolncrementStep 192, 193, 197,
237, 238, 423, 490, 502
- Cache 542
- Caption 237, 238
- CaseSensitive 221, 228, 229
- ChildColumns 281, 282
- ChildKeyConstraint 282
- ChildRelations 228, 229
- ChildTable 282
- ColumnMapping 23", 239
- ColumnMappings 11, 138, 159, 461
- ColumnName 215, 237, 239
- Columns 12. 178, 228, 229, 250,
251, 252
- CommandText 9, 83, 97, 105, 107.
155, 377, 378, 387, 406,411,415,
471,476,479
- CommandTimeout 107
- CommandTVpe 9, 96; 97, 105, 107,
109, 150, 474,476
- Connection 9, 54, 72, 83, 101, 105,
107
- ConnectionString 6, 63, 64, 67, 74
- ConnectionTimeout 67
- ConstraintName 250, 251, 252
- Constraints 12, 228, 229

603

ContinueUpdateOnError 158, 162,


223, 438
Count 301, 307, 308
Current 313, 506
DataAdapter 395
Database 67, 68
DataMember 503, 504, 536
DataSet 187, 228; 230, 282
DataSetName 177, 221, 222, 460
DataSourcc 67, 68, 503, 509, 536
DataTable 460
DataType 120, 178, 188, 237, 239
DataView 315, 506
DataViewManager 307, 309
DbType 120, 122, 125
Default 13
DefauttValue 210, 237, 240
DefaultView 228, 230
DeleteCommand 11, 35, 138, 158,
159, 363, 378, 381, 388, 407, 420
DeleteRule 251, 277, 279
Depth 114, 119
DesignMode 221, 222, 228, 230
Direction 10, 98, 120, 121
Display-Member 509
Driver 68
EnforceConstraints 221, 222. 291,
466
Expires 539
Expression 13, 197, 237, 240. 274,
503
ExtendedProperties 221, 222, 228,
230, 237, 241, 250; 251, 252, 282
HieldCount 114, 181
Fields 178
Filter 17
GetName 181
HasErrors 221, 223, 228, 230, 243,
248
InsertCommand 11, 35, 138, 158,
159, 363, 374, 380, 381, 388, 407,
416,418,420
IsClosed 114
IsEdit 315
IsNew 315

604

- IsNullable 120
- IsPrimaryKey 250, 251
- Item 14, 15, 86, 88, 114, 181, 200,
202, 243, 307, 308, 315
- ItemArray 203, 243
- Locale 221, 223, 228, 231
- MaxLength 183, 189, 197, 215, 237,
241
- MinimumCapacity 231
- MissingMappingAction 148, 158,
161, 163
- MissingSchemaAction 150, 151,
158, 161, 163, 185
- MissingSchemAction 161
- Name 178, 491
- Namespace 221, 224, 228, 231, 237,
242, 461
- Nested 282,461
- OleDbType 120, 122, 125
- Ordinal 178, 237, 242
- PagerS tyle 546
- ParameterName 120
- Parameters 107, 109
- ParentColumns 282, 284
- ParentKeyConstraint 282, 284
- ParentRelations 228, 229
- ParentTable 282, 284
- Position 494
- Precision 120, 122, 167, 397
- Prefix 221, 224, 228, 231, 237, 461
- Primary-Key 146, 189, 218, 229, 231.
515
- Provider 67, 68
- QuotePrefix 395
- QuoteSuffix 395
- Readonly 13, 183, 189, 238, 242.
500
- RecordsAffected 91, 92, 114, 115
- RelatedColumns 251, 252
- RelatedTable 251, 252
- RelationName 282, 284
- Relations 16, 221, 224
- Row 315
- RowError 243, 244
RowFilter 307, 309

- Rows 12, 200, 229, 232


- RowState 162, 201, 207, 243, 244,
300,431
- RowStateFifter 300, 307, 309
- RowUpdate 441
- Row-Version 315, 316
- Scale 120, 122, 167
- SchemaPath 477, 479
- SelectCommand 11, 32, 137, 139,
H I , 144, 155, 158, 159, 163, 167,
362, 375, 380, 381, 390
- SelectedValue 509
- ServerVersion 67, 68
- Session 541
- Size 120, 122, 125, 167, 397
- Sort 17, 303, 307, 310
- SourceColumn 120, 122, 363
- SourceVersion 120, 122, 363
- SqlDbType 122
- State 67, 69, 78
- Table 181, 238, 242, 243, 244, 250,
251, 252, 299, 307, , 316
- TableMappings 11, 138, 146, 158,
159
- TableName 186, 229, 391
- Tables 221, 224
- Text 492
- Transaction 99, 107, 109, 388
- Type 13
- Unique 13, 183, 184, 189, 238, 242
- UpdateCommand 11, 35, 138, 158,
159, 363, 380, 381, 388, 405, 407,
419, 420
- UpdatedDataSource 407
- UpdatedRowSource 107, 109, 408
- UpdateRule 251, 277, 279
- Value, 120 121, 205
- ValueMember 509
- ViewState 539, 540
- VirtualltemCount 547
- XslPath 478, 484
323
448
46, 48, 49, 61

58

10, 55, 99, 388, 444


- 445,446
- 44
Y

- 18
- 3, 349, 351

- . DDL
- . DML

6, 7. 81

605

^7 (David Sceppa)
Microsoft Press. 2000 . Programming ADO".
, ,
,
, .
Visual Basic .NET
.
Microsoft, , ,
microsoft public.dotnc-tframework.adonet, ADO .NET.
SQL Server
(), - Melbourne
Cricket Grounds.
, , , , . - (.
) . ,
, -. , ,
, ,
- . , < (Psycho Steve DuMosch), -,
, (New England Patriots)
, , , \' (Ray Borque),

MICROSOFT
( -)

. ( ) , ( ) Microsoft
Corporation ( Microsoft*) Microsoft, ,
( ). ,
, , , , . , .
, ,
- .

, ,
1.

. :
a) . . , , '[ .
b) .
, ,
, .
.
c) License Pak. Microsoft License ,
,
, , . .
, .
d) . , ( "), .
i) . Microsoft (d)(iii) .
, .
ii) . (d)(iii) Microsoft
, (
), Keadmc. , ,
iii) . , , , : ) ; ) , Microsoft ; )
; )
" Microsoft ,
, ; ) . Microsoft.

2.

, .

, , , ( , ) , .
.
. .
. , .
. Microsoft ( )
( ). Microsoft, , / , Microsoft. , ,
. , Microsoft , Microsoft
, .
, Microsoft .
.
, , , , ,
( , , . , )
.
. Microsoft
, .

.
3.

.
( , , , , , , , , , )
Microsoft .

. . ,
, , ,
, . , , .


( ') - . MICROSOFT ,
.
.
MICROSOFT. , ,
, , - ( , . , , ) .
MICROSOFT ,
, .

(),
( , ) ,
.
- , , Microsoft , , Microsoft : Microsoft Sales Information Center. One Microsoft Way.
Redmond. WA 98052-6399.


Microsoft ADO.NET

. .
. .
. .
. .
. .

-
Adobe PageMaker 6.0

TypeMarketFon/ii'brary

L E G A L

USE

. .

*
1210S7, , . , .9
.; (095) 142-0:571, ./: (095) 145-4519
e-mail: mfo@rasedit.ru, http:// www.rusedit.ru


11.03.03 . 3 000 .
70x100/16. . . . 40

107105, , . , 46


.: (095! 142-0571; ./ (095) 145-519
e-mail: mfo@ruseditrij; http:// w^iv ruseditrj

( , - )
,
,
, ,
. .





ADG.NET

SQL Server


MSDN Magazine
Microsoft MSDN Library

, 1:
Microsoft ADG.NET, Microsoft SQL
Server,
.
400 ., 2003 .

.

.NET Framework ( ,
, ,
..),
,
.NET, /
.

ASP.NET

MSDN Magazine

www.rusedit.ru almanah@rusedit.ru.

MSDN Library,

, 2:
Microsoft ASP.NET, .
400 ,, 2003 .



: .: ;095| 142-0571. e-mail: sale@rusefllt.ru;
-: htlp:// wiww.ITbooit.rij. .: (095) 145-4519



MSDN Magazine/
:

Web: ,
t Web.
XML XML
(XML Schema, VS-Secunty. Web . .}] .
ASP '
ASP ASRNET.

^
,
,
ADO.NET.

{SOAR -, .NET Framework
.),

.NET
.NET ,
8,
,
,

- ,

. ! ;;
'
'. " .
.
(,$!
.
.

Microsoft,
.


,

,
. ^^
\ m .

Microsoft."

'

,
Microsoft
("MSDN Magazme/ -,
1, 2002 r.J


MSDN Magaztee/ -
w ww.microoft.com/ rus/msd n/ magazine



.


-

www.ITbook.ru

:
-
-

-

- ,

- ,

- CD-

mfo@bar4nsoft.rM

:
Hord'n'Soft - 73140, Hoid'n'Soft + CD - 26067