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 / . .
, , , , , , .
, - ,
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
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 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
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,
I Microsoft ADO.NET
.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,
,
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 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-.
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
, :
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.
, UserName,
, , , , . ADO , . ,
OLE DB- ?, ?, ? ?.
,
.
DataSet ADO.NET
. ADO.NET . ,
ADO.NET .
DataSet
, .
1 ADO.NET
19
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:
Class Library
Windows
ControlLibrary
Application
j Chapters]
Location;
. 2-1.
OK
Cancel
Windows-
23
Windows Form
Class
Component
Class
User Control
DataSet
XML Fie
Open
XML Schema
Caned
I Microsoft ADO.NET
24
. 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,
25
Wizard
a data connection
. 2-5-
. 2-6.
I Microsoft ADO.NET
26
,
. .
3.
, SQL Server, Provider
OLE DB.
OLE DB. Data Link Properties .
. 2-7.
SQL Server MSDE, Access- Northwmd, Microsoft Jet 4.0 OLE DB.
Next, Connection (. 2-8).
. . .
Choose Tables Or Views Dara Form Wizard (. 2-9)
, . ,
DataTable ADO.NET. , , .
Available Items
Selected Items, . - Selected Items,
. ,
, .
Ltioose tables or views
EmployeeTeirilof
Ordai Detalk
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.
29
you olspdav more Chan ^ table on the form, [he tetdes ha*E a f attBi
. 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 .
. 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
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
1
tdti
ThrOT
FlnnllJ
He . oiei:o
End Tcy
End 3ub
Cionl. Closed
. 2-16.
ots
chs
-INS
, DataSet
,
Add , Delete . .
Dafafle/at/on
, .
.
- DataRelation ( ) ->
, . ,
.
', . Northwind,
(CustomerlD} ALFKI .
CustomerlD Chap2. He :
.
. : CustomerlD Chap2. DataRelation DataSet CustomerlD
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
35
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,
.
37
OleDbDataAdapter, DataAdapler,
. ,
, Data Form Wizard. .
, Windows Form Designer generated code
(. 2-20). . , InitializeComponent, , DataAdapter Configuration
Wizard. .
OMWo.ml.rt I
Gill
Oil
. 2-20. ,
38
Microsoft ADO.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
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
43
Visual C# .NET
SQLDMO,SQLServer dioServer = new SQLDHO.SQLServeK);
dmoServer.LoginSecure = true;
dmoServer.Connect("Clocal)\\NetSDK", null, null);
System.10.Streamfieader filSqlScript;
string strPathToFile;
. , ,
44
II : .NET
Connection
OleDbConnection .
OleDbConnection, :
Visual C# .NET
OleDbConnection en;
en = new OleDbConnectionO;
OleDbConnection
.
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
-
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 * . , , :
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 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;
, :
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
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)
2.1
1,0
1.0
1,0
1.0
1,0
1,0
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
50
II
: .NET
QleDbConnection , . , Open OleDbConnection:
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-
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
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
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
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);
58
II
: .NET
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());
59
'% KEP5ERVEP
& SCEP5ERVER\NE7S:
"A SC?iRVR1,VSRe
-6.
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
. 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.
64
II
: .NET
OleDbConnection,
.
'Properties
"; (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
. 3-12.
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
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()
71
Visual C# .NET
OleDbTransaction txn = cn.BeginTransaction{);
Visual C# .NET
OleDbConnection en = new OleDbConnection(strConn);
cn.0pen();
en.ChangeDatabase("Northwind");
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()
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
4-5956
74
II
: .NET
DataTable tbl;
tbl = en.Get01eDbSchemaTable(01eDbSchemaGuid.Columns, objRestrictions);
Restrictions
OleDbScbemaGuid MSDN.
GetOleDbSchemaTable DataTable ( ), . DataTable . ,
GetOleDbSchemaTable:
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/
%! Mudufel.vfa |
ule Hodulel
Dial UlthEve
sub HeinO
en - 01
cn.QpenO
cn.ciosei;
Sub
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
,
. 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
Command
Command .
, . , Command .
Command
Command. New . Connection.
CreateCommand Connection ( 3):
82
II
: .NET
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
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 C# .NET
OleDbDataReader rdr = cmd.ExecuteReaderO;
88
II : .NET
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
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
91
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
ExecuteScalar ,
, , , .
, ,
, . 20 , 20
, , ,
. , . , :
SELECT OrderlD, CustomerlD, EmployeelD, OrderDate
FROM Orders WHERE CustomerlD = ?
.
SQL Server .NET ? @. Customer ID :
95
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 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 ,
.
. ,
,
:
,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
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
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
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
Server Explorer
Command , Server
Explorer . SQL
Server SqlCommand,
OleDbCommand.
. 4-6 Windows- CustOrderHist
SQL Server North wind. Properties , CommandText,
CommandType Connection ,
. WindowsApaUr.it1
? 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
5-5958
106
: .NET
Orertiofi
Input
. precision
i Scale
.- SourceCokimn
\ SourceVersion
Current
'Fat' i
Ualue
1
'
i ParametsrPJame
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
,
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*
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
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 C# .NET
OleDbDataReader rdr = cmd.ExecuteReader();
object[] aData = new object[rdr.FieldCount];
while (rdr.ReadQ)
{
rdr.GetValues(aData);
Console,WriteLine(aData[0].To8tring());
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 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
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
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,
:
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())
{}
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 '
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
, . . ,
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
. ADO ADO.NET.
Refresh Parameters ADO,
ParameterCollection ADO.NET?
. Refersh ParameterCollection , , .
ADO.NET .
.
CommandBuilder ( 10) DeriveParameters, Parameters Command,
, , .
128
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.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
*
' 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
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
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);
!
catch (Exception ex)
:
if (blnCancelledQuery)
Console. WriteLine( "Query cancelled");
else
Console. WriteLine( ex. Message);
cn.CloseO;
blnRunningQuery = false;
blnCancelledQuery = false;
5
DataAdapter
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
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,
FROM Employees
5 DataAdapter
1 19
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 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
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
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
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");
148
II
: .NET
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
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.
II : .NET
152
^ Wn>duvra*|iplir4tion1
Edit
Mirrisafi v,iwl [
lefm1.vb|[Jeiignl
Bow ftojKt
. 5-3.
DataAdapter
.1.
. 5-4.
DataAdapter
SQL- (, SELECT CustomerlD, CompanyName FROM Customers) . Data Adapter Configuration Wizard . SQL-. -
5 DataAdapter
153
. 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
. 5-6.
154
II
: .NET
Run.
. 5-8 Query Builder. , .
. SQL , .
.
. 5-7.
. 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
Dels*:
f GFavasd sEiEC'
* Generrted table
* Gnnaralcd TER3 tiacemert.
' Gtaersea UPDSTE .
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
Wong
Bull!
Elgin
GHEAL
IRA1H
SPIIB
Lander
LONEP
IcnesomePri FranWfcnn
Portland
,EBI
"LETSS
WHITC
WZVK
Portland
San Frsn
While Clover
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
160
II
: .NET
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");
, DataAdapter
DataSet, TableMappings?
DataAdapter , . :
DataAdapter
161
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,
:
164
It
: .NET
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 , ,
( ), DataAdapter 10 .
( ) , DataAdapter ,
.
?
. , 100
10 10 . ,
10 . , 10 10 . : ,
20 . 100 -
DataAdapter
165
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
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
DataAdapter
. 5-3 , DataAdapter.
5-3.
'
RoivUpdating
RowUpdated
OleDbDataAdapter
, DataSet DataTable
DataAdapter -
FillError
DataSet DataTable DataAdapter
, FillError.
DataAdapter
169
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 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
,
. 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
DataSet -
. DataSet DataTable DataRelation.
DataTable DataRow, DataColumn Constraint.
, DataSet.
.
DataSet
DataSet New . DataSet
, DataSetName
.
,
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
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
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";
, 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
DataTable Rows,
DataRoiv, DataTable. , '
DataRow .
DataRow
DataRow DataTable. DataRoiv
DataTable, Rows .
DataRowCollection, DataRow.
-, DataRowCollection , .
Fill DataAdapter DataTable,
DataRoiv
.
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
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
. North wind
. CustomerlD Customers 5
. Orders
6 DataSet
183
OrderlD , CustomerlD
Customers.
. , - . ,
.
,
. , , . , Web- , , , . .
DataSet ADO.NET , . ,
(constraints),
,
DataColumn,
DataColumn .
Readonly
,
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
Constraints DataTable
DataSet
DataTable. ADO.NET ,
DataTable, UniqueConstraint ForeignKeyConstraint; Constraint. DataTable
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
, ...
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
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
Visual C# .NET
DataSet ds = new DataSetC);
, 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;
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));
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)
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
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
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"
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
,
, . , Order Details
North wind
, .
, ,
.
,
. ,
:
SELECT OrderlD, ProductID, UnitPrice, 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.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
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
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 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
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.
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);
6 DataSet
207
Ron' , ADO.NET ,
. , .
:
UPDATE HyTable SET FieldToHodify = NewValue
WHERE PKField = PKValue AND FieldToHodify = OriginalValue
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
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
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
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).
212
N1 : DataSet ADO.NET
ftddlhisdataset tolhecteiigriei-.
6 DataSet
213
Microsoft Sis
. [design] Forml.sMlteiign|
e*
.I e
. 6-3-
DataSet
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
! Dataset2.xsd
Open
. 6-5-
DataSet
6 DataSet
I E.
215
NewglsmafiE
New cranplexType
New srnpleType
New group
^,
New attributeuroup
<;
New any
Generate Dataset
Preview Dataset...
. 6-6.
DataTable DataSet
. 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
. 6-8.
DataColumn
Help
. 6-9. DataSet
DataSet. DataSet DataSet.
: DataSet , DataSet . . 6-10
Visual Basic .NET DataSet.
6 DataSet
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
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
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
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
DataTable Locale.
Locale DataSet
English (Australia):
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
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
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
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
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
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
236
III
: DataSet ADO.NET
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
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 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 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
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
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,
.
244
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
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)
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
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
ConstraintName
DeleteRule
ExtendedProperties
RelatedCoIttmns
RelatedTable
Table
UpdateRule
String
Rule
PropertyCollection
DataColumn
DataTable
DataTable
Rule
252
III
,
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 C# .NET
if (tbl.PrimaryKey. Length > 0)
// DataTable
else
// DataTable
DataSet Dispose?
254
, Dispose - , , .
Dispose DataSet Dispose
DataTabte DataSet.
256
Employees
E Employee'lD
La^iMane
FntrvVKI
Customers
~
CornDanvNamf
"^ COTeetTt*.
-.*i;i.
risiomerlD
EmployealD
^QrderDite
3hlpptete
3l*Vn
Prwrjhl
~CU
PostalCode
J*
__ 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
, ;
. (, 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
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
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
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
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
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:
270
. 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
, , ,
. ForeignKeyConstraint,
.
, , . .
pubs titleauthor (. 7-5), .
, au_id title_id
authors titles .
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
{
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
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)
{
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.
. 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
280
define -Atiorship (toyref), select etemert and Vey, selt th9 cMd element,
nd rher. *elKt*ta child * <[* each potent field.
Data* Properties
. 7-8. DataRelation
Edit Relation
Eto
E*
.**
&*
e*ug
5|
Sindm*
l! -
- S' ? .S- fe ^
tttp
eljijo
PtdpHfei
fbjitmrieriorderi
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
...
ggmowe j
Close
M'rT
DataRelation
, DataRelation . - ,
. - .
DataRelation
DataRelation .
DataRelation. . 7-1 DataRelation.
ChildColumns
CbildColumns , DataColumn
DataTable.
.
282
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
ds. Tablest"Customers"].EndLoadData();
ds.Tablest"Orders"].EndLoadData{);
8
, ,
DataTable
DataTable . . Find,
. , Select, , , .
, , :
290
III
: DataSel 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);
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
else
,
. , (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
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 :
) & "'"
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 C# .NET
strCriteria = "[Bad\\]Colunin[Name] = 5";
, * \ . strCriteriaFilter
"[Bad\]Column[Name] = 5"
, - ,
, - . DataTable
, .
, .
8 , ,
295
Select
ADO.NET, Select .
, , , (, ).
.
, Select,
DataTable , . DataRow, Select, .
SQL- , ,
ORDER BY. , , City:
296
III
: DataSet ADO.NET
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
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
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 :
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);
vue.RowStateFilter = dvrs
vue = New DataView(tbl, "Country = ' U S A ' " , "City DESC", dvrs)
300
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"]);
,
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
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
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
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 , ,
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
DataView
. AllowDelete, AllowEdit AllowNeiv
, . , DataView.
True,
308
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:
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
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
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
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
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
DataRoivView. DataRowView
DataRow.
RowVersion
DataRoivView
, Item,
RowVersion DataRowView.
RowVersion ,
DataRowVersion.
DataRowView
DataRoivView . 8-5.
8-5. DataRowView
DataView,
, ,
317
,
.
DataTable?
. , . :
31 8
lhalPMiNMCiilt.
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 .
8 , ,
Do
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
,
Visual Basic. .
, .
, Microsoft Visual Studio
,NET DataSet .
:
324
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");
326
III
: DataSet ADO.NET
. MS-DOS :
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 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
. 9-1-
DataSet
DataSet DataSet
. DataSet, ,
, , , DataRelation.
.
Solution Explorer . XML Schema
Designer Orders Add\New Relation.
Edit Relation (. 9-2). , .
. , . .
DataSet
, , DataSet
Data .
328
?
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
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 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
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 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.
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
'
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")}
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;
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
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
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
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 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
. 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)
>
,
. ADO.NET , : Update requires a valid DeleteCommand when passed DataRow
collection with deleted rows* ( Update, DataRow , DeleteCommand).
10
349
ADO.NET, ,
, ADO.NET, ADO. ADO.NET, ADO .
, ADO * ,
, ADO.NET . , ADO , , ADO.NET.
ADO , DataSet ADO.NET. Recordset ADO . , Recordset
ADO .
, :
*
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
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 '
Visual C# .NET
static OleDbCommand CreateUpdateCommandQ
{
string strSQL;
strSQL = "UPDATE [Order Details] " & _
SET OrderlD = ?, ProductID = ?, " +
Quantity = ?, UnitPrice - ? " +
353
354
'
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
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";
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
" &
359
360
111
: DataSei ADO.NET
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();
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;
" +
1 3-5958
361
362
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
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
ProductiD
Quantity
LJnitPrice
10503
65
20
21.05
DstaRow
( )
10503
65
40
21.05
QrderiD
ProductlD
Quantity
UnitPrice
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 " & _
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
10
367
, 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
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
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
10
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
371
372
}
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" +
10
373
. 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 " & _
Visual C# .NET
string strConn, strSQL;
strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
10
375
, , :
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
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
Generated SELECT *.
Generated tabk mssamgs,
SenestKJINSEM ateinert.
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,
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.
Data Adapter Configuration Wizard
DataAdapter, SQL Server . Choose A Query Type
Use Existing Stored Procedures (. 10-6) Next.
380
Ml : DataSet ADO.NET
fffrtrnew jDrcdprocedure
Choose er. *risif g oied pfOure for each opeuten (tat. !, update snd
It},
. 10-7.
SelectCommand DataAdapter
10
381
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;
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
.
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'
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
CompanyName
UPDATE:
UPDATE Customers
SET CompanyName = 'New Company Name'
WHERE Customer-ID = 'ABCDE' AND
CompanyName
ContactName
ABCDE
Original Contact
CustomerlD
CompanyName
ContactName
ABCDE
New Contact
CustomerlD
CompanyName
ContactName
ABCDE
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
Phone
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
, true,
, NULL NULL.
, DataAdapter Customers
CustomerlD, Company-Name, ContactName Phone. CustomerlD CompanyName
, ContactName Phone NULL. , WHERE
NULL. -
388
,
, . .
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
ADO.NET :
Visual Basic .NET
Dim strConn, strSQL As String
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 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
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);
Visual C# .NET
OleDbDataAdapter da = new 01eDbDataAdapter(strSOL, strConn);
da.TableMappings.Add("Table", "Order Details");
10
393
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")
394
Visual C# .NET
QleDbDataAdapter da = new 01eDbDataAdapter(strSQL, strConn);
//
DataSet ds = new DataSetQ;
da,Fill(ds, "Order Details");
//
da.Updatefds, "Order Details");
//
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
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();
{
Console.WriteLine{pa ram,ParameterName);
Console. WriteLine("\t" + param. Direction. ToStringO);
Console.WriteLine("\t" + param.OleDbType.ToStringO);
Console.WriteLine();
RefreshSchema
,
DataAdapter, , , RefreshSchema CommandBuilder.
CommandText SelectCommand.
DataAdapter, - DataAdapter
. CommandBuilder , , , . ,
DataAdapter }' CommandBuilder , CommandBuilderRefreshSchema.
CommandBuilder . , , . CommandBuilder DataAdapter Update Get<Update/Insert/Delete>Command
CommandBuilder,
398
,
. , 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
400
III
: DataSet ADO.NET
,
:
SELECT * FROM [Order Details] HOLDLOCK WHERE OrderlD = 10503
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
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 = ?
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
spUpdateDetail
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
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, .
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
nsert succeeded!
Update succeeded!
Ddete succeeded!
. 11-1.
Timestamp
SQL Server, Access, Sybase ,
IDENTITY (IDENTITY columns). -
11
411
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
412
III
: DataSet ADO.NET
, 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)
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
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
. 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
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
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
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
DataSet,
. .
,
, , . . .
DataSet
. , DataSet ,
.
, , . :
Northwind ,
.
DataSet ,
. , .
11
421
. Northwind
, , .
.
, . Northwind ,
Order Details.
, , .
Visual C# .NET
CustoinersAdapter.Update{MyDataSet.Tables["Customers"]);
OrdersAdapter.Update(HyDataSet.Tables["Orders"]);
, '
, DataAdapter, Orders, , , .
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
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.
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
Thomas Hardy
>
DataSet
Gi. stcrneni)
Company-Name
TSCo!
Alfreds Ftitterkiste
Hw
>
ANATR
>
ANTON
Antonio Moreno
Antonio Moreno
AROUT
Horn
Mew Contact
>
ftUHd
ALFK1
Alfreds Futterkiste
. 11-6.
Web-
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
. 11-8.
Column A
GDhmiB
ColumnC
2nd
Main
2nd
2nd
Main
2nd
Main
Mafr
(null)
2nd
(null)
2nd
Merge DataSet
430
DataSet
CompanyName
dontaettee
TSCol
ALFKJ
Alfreds Firtterkiste
New Contact
<0 ?
ANATR
AnaTrujttlo
AnaTrujillo
<0 ?
ANTON
Antonio Moreno
Antonio Moreno
<0 ?
AROUT
New Contact #2
<0 ?
vOustonwiD, =.:
CustomejID
Name
j Contat'tHame
ALFKI
Altreds Futterkiste
New Contact #1
<Hoeoe ?
AR OUT
New Contact #2
< ?
TSCol
GompanyName
TSCol
ALFKJ
Alfreds Ftfierkjste
New Coritad #1
< >
ANATR
AnaTrujillo
AnaTrujiilo
<0 >
ANTON
Antonio Moreno
Antonio Moreno
<0 ?
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
;;
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
' 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
:|
-\
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
DataSet , . ,
.
DataSet
, , .
Merge , ,
,
DataSet , . , , .
11
435
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
Custamerio
10643
ALFKI
09/22/1997
10692
ALFKI
10/31/1997
12000
ALFKI
02/24/2002
12001
ALFKI
02/24/2002
EmptoyeelD
QrderDate
PseudoKey
436
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, .
rubrrdtoj 11
. 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
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");
, , ,
. , , ,
,
, . 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 C# .NET
private void HandleRowUpdated(object sender, OleDbRowUpdatedEventArgs e)
(
if ((e.Status == UpdateStatus.ErrorsOccurred) &&
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;
....
,
. 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
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
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
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
Visual C# .NET
[AutoCompleteO]
public void MyTransactionalMethod()
(
, , . : , ,
,
DistributedTransaction
-
( Visual Basic .NET Visual *.NET), . ,
Connection ADO.NET.
. , , , . (. 11-19) .
, ,
, .
452
III
: DataSet ADO.NET
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
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
. 12-1. DataSet
XML- GetXml
3 ;iKiima.>:HL - Inien
. 12-2.
'6-3958
458
IN : DataSet ADO.NET
'
Navigate InternetExplorer . * . Type Missing.
DataSet ReadXml,
DataSet . , WriteXml
, Stream. TextReader XmlReader. , ReadXml XmlReadMode, XML.
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
. 12-3. XML-
1996-07-3DTOO: 00:00.ooaaoaa-D7;oo
MfHjiUriilprice-'^.B" /.
- 1 997-1 -:00:00.0000000-:00'
. 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
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);
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
(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);
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"
468
SELECT X Customer ID
SSL AUTO, EI.EHSMTS
; <i.
Query tat*
12 XML-
469
Visual C# .NET
//
using System.Data.SqlClient;
using System. Xinl;
string strConn,
strSQL;
, , , 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);
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
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>
474
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.
12
XML-
475
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
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
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
482
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 *^
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
Product
1
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-.
12 XML-
485
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-
, .
,
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).
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 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)
System. EventArgs e)
System. EventArgs e)
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);
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
else
MessageBox.Stiow("No changes to submit!", "SubmitChanges",
MessageBoxButtons. OK, MessageBoxIcon. Information);
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 = ?
13 Windows-
503
DataRelation, DataTable
OrderlD. Solution Explorer .xsd-
, XML Schema Designer.
CustomerlD DataTable Orders DataTable Order Details. .
I,' '--''.
Orders (daOrders)
Cancel
Help
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
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 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 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
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
13
Windows-
End If
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);
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
516
IV ADO.NET
.
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
, .
DataAdapter .
. DataAdapter fill DataAdapter.Update DataAdapter
, ,
, .
.
,
.
. , , . ,
, . , .
. . ,
DataAdapter . :
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;
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
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
{
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 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
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
, , ?
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
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.
, 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.
DataGrid
Windows- DataSet , . DataSource DataMember, DataBind DataGrid. Windows- DataGrid .
Web- . DataGrid DataBmd . ,
DataBind ; .
DataGrid DataReader
, Web- .
DataSet ( , .),
Web. ASP.NET
DataReader.
14
Web-
537
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;
!
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)
i
else
{
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-. . , .
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
. 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
gridfiesults.DataSource = rdrOnePage;
gridResults.OataBindO;
rdrOnePage. CloseO;
cnNorthwind.CloseO;
10 , .
, .
?
,
Fill DataAdapter
5, Fill DataAdapter
,
DataAdapter. , ,
.
, 10 . 40 10. DataSet :
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
14
Web-
551
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
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,
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 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>
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
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
//
.NET
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 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();
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
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;
564
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;
.NET
567
, 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
BY
'PROCEDURE')
SPECIFIC NAME
SQL
Server Books Online.
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.
.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
!
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
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,
OracleDataAdapter
OracleDataAdapter
DataTable .
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 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
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";
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"
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
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
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
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);
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
, Ad Hoc Query
Tool, - ( ). . -2 Ad Hoc Query Tool , .NET . , OrderDate DateTime OdbcType.
20
595
586
. -2. .NET
Ad Hoc Query Tool
588
,||....
Connect.
(. -2),
.NET.
Connection String.
jProvider=50LOLEDB.Data Souce=(local]\NetSDK;l
. -2.
.NET
Ad Hoc Query Tool
, Microsoft .NET Framework OLE
DB .NET Data Provider SQL Client .NET Data Provider. .NET.
.NET, Microsoft .NET Framework,
589
Resouice Nam*
radeDienJ
Delimiters
Ptefi*
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.
, .
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
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
( AtKI.MIl nil M
lokwiNsme
. -5.
Cdi-fnnlDrdrr
ColuronBize
Picn-ide'ipe 0*0bTjpe
1*UOHS
591
, , , 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
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\, .
Jv Stmg
593
. -.
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
. -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
Rowl ol 91
AddHew J_
FHI
Delete
Submit
JJjH
Cancel
Discaid
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,
,
596
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
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
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
- 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
- 85, 93
- 20
65
2, 11, 12, 18
VIC
600
0
82
. CLR
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
603
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
- 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