Академический Документы
Профессиональный Документы
Культура Документы
ADO .NET
, 08080165
. .
. .
2009
681.3(075)
22.18 7
P 13
:
(. . .-. ,
. . );
,
. . .
-
P 13
C#.
DO .NET: / . . . , . . .
: , 2009. 170 .
ISBN 978-5-9795-0475-9
ADO (ActiveX Data Object) .NET
#. Microsoft Access
Microsoft SQL Server; SQL,
ADO .NET.
, ( 080801
( )) ,
, .
681.3(075)
22.18 7
ISBN 978-5-9795-0475-9
. ., . ., , 2009
. , 2009
2
..................................................................................................................................5
1. ......................................................................................................7
1.1. .............................................................................7
1.2. .............................................................8
1.2.1. .................................................................................................9
1.2.2. .........................................................................................................10
ER- ......................................................................................................................10
, ...............................................................................................11
.......................................................................................................................13
1.2.3. ........................................................................................................15
1.3. Microsoft Access ...............................................................................15
1.3.1. ..........................................................................................................................15
1.3.2. ..............................................................................................................................17
1.3.3. ...............................................................................................................................18
1.4. Microsoft SQL Server........................................................22
1.4.1. .........................................................................23
1.4.2. Microsoft SQL ...........................................28
1.5. 1.....................................................................30
2. SQL ....................................................................................................................32
2.1. SQL- ......................................................................................33
2.2. SQL ...................................................................................36
2.3. like ........................................................................................37
2.4. SQL .........................................................................38
2.5. DML ...........................................................................39
2.6. 2.....................................................................41
3. ..........................................................................................42
3.1. ..................................................................42
3.2. ADO .NET ..................................................................................................53
3.2.1. DataSet..............................................................................................53
3.2.2. ( DataTable DataColumn) ..................................................53
3.2.3. DataRelation ....................................................................................................53
3.2.4. ( DataRow)..............................................................................................53
3.2.5. DataAdapter .....................................................................................................................54
3.2.6. DBConnection DBCommand .......................................................................54
3.3. Server Explorer .......................................................................................................................54
3.4. ...................................................................56
3.5. 3.....................................................................58
4. ADO .NET...................................................................................................................59
4.1. .................................................................................................59
4.1.1. ConnectionString ........................................................59
4.1.2. . Connection ............................................................60
4.1.3. Connection.........................................................................................61
4.1.4. .................................................................................................64
MS SQL ..........................................................................................................64
MS Access ......................................................................................................65
4.1.5. ...........................................................................................65
4.2. ...........................................................................................................67
4.2.1. ...........................................................................................68
4.2.2. ...................................................................................................70
3
4.2.3. ...............................................................................74
4.2.4. Management Studio..................................................80
4.2.5. Visual Studio 2008 ...................................................82
4.3. .........................................................................................................85
4.3.1. SQL- CommandText...........................................................85
4.3.2. Command ...........................................................................................................86
.................................................................................................86
CommandType CommandText..........................................................................88
ExecuteNonQuery......................................................................................................89
ExecuteScalar.............................................................................................................93
ExecuteReader ...........................................................................................................95
4.3.3. ....................................................................................97
ExecuteNonQuery ..........................................................................98
ExecuteScalar ...............................................................................104
ExecuteReader..............................................................................104
4.3.4. .........................................................................................108
...........................................................108
...................................112
SQL- ...............................................113
4.3.5. ....................................................................................................................115
ADO .NET ...................................................................................................119
4.4. ...............................................................................................123
4.4.1. DataSet, DataTable DataColumn................................................................123
DataTable DataColumn ...........................................124
PrimaryKey .........................................................................................................126
UniqueConstraint ForeignKeyConstraint..................................................127
, .............................................................128
.........................................................................130
.....................................................................................................132
4.4.2. DataRow ...........................................................................................................133
....................................133
RowState .............................................................................................................137
RowVersion ........................................................................................................138
DataTable ..............................................................................................143
4.4.3. DataGridView...................................................................................................145
DataGridView.........................145
DataGridView ..................................149
4.4.4. DataView ..........................................................................................................149
...........................................................................................................150
............................................................................................................151
.....................................................................................................................152
4.4.5. ............................................................................................157
HashTable .................................................................................................................157
ArrayList ...................................................................................................................158
4.5. 4...................................................................160
...................................................................................................................................162
...............................................................................................................167
.......................................................................................................170
080801065 ( ) , ( ).
..03
..04
(). . .
. . .
. XML-. . . .
. . (L). . L-.
, .
. . . .
.
.
: , ,
- .
-
: - ;
; ; ; ; ; . .
. , . ; ; .
. . . . ; .
(), ,
(L-)
ADO (ActiveX Data Objects) .NET C#.
- .
ADO .NET . , # Windows .NET.
# Windows .NET.
Windows- .NET C#,
.
4- .
.
: ( ), , ,
, , . ., ,
. .
SQL (Structured Query
Language) SQL Management Studio.
Visual Studio 2008 .
, , .
ADO .NET.
ADO .NET, : .
C#. [11, 8].
, ,
, (
).
.
6
1.
1.1.
()
, , , , . ,
, , , .
, . (, , , ), (, ,
, ).
. ( ), (. 1). (,
, , ).
. , .
. 1.
7
(). :
( );
;
.
, . (, ) .
.
:
;
;
;
,
.
. , . ,
(SQL Structured Query Language).
,
.
1.2.
,
, , , . , , ,
. ., .
, , , .
.
.
: , .
8
. , .
.
() .
.
. . ,
(), , . ,
, .
1.2.1.
. ,
, .
. , . 1.
1
, . , , , , , .
,
, ,
, .
, , :
, 2
, , 2 7 . , 3 . .
.
, ,
, , .
. .
, ,
, .
, . .
1.2.2.
ER-
ER- (Entity-Relationship -).
, , .
5 :
10
:
() .
(
,
, ,
).
.
.
ER,
. 2.
. 2. ER-
,
. ,
, .
, , . 2.
2
, . , . ,
. , ,
. ER- 11
, , , . -
.
. relation () relationship ( ).
, .
() ,
.
,
.
(), ,
. . . (). , ( )
.
, ,
. , ( ) . ,
.
(. 3).
,
. , , , .
3
12
, . ,
, , . , , ( )
(
). , ,
. , .
, .
().
(1) .
, ,
, .
(2) , .
, .
(3)
.
(4) .
1, . 2,
( , . .), 2 .
.
,
. ,
. .
,
?
13
.
, , ,
(. 3). , -, ,
. - .
1
1
. 3.
,
. , ,
2
--. , , , , . , , : , ,
, , . 3.
.
,
(, , ., ), , . ,
. ?
2 .
( ),
( ), . , .
14
1.2.3.
. ,
Oracle, , , , ,
.
Microsoft Access Microsoft SQL Server
2005 Express Edition.
. 4.
. 5.
15
1:
,
. (. 5).
,
. (. 6).
. 6.
Microsoft Access 4.
4
Microsoft Access
OLE
, , ,
, , , , . 255 .
(FieldSize) ,
, 255 . 65 535 . (Text) ,
, , . (, . .). MEMO
, , (
). 1, 2, 4 8 . (FieldSize)
. 8
. 8
( 1) . 4
, ,
, /, /, ./.. Null
. 1 .
OLE (, Microsoft Word,
Microsoft Excel, ,
) ( )
16
.
URL. 64 000
,
, .
. 4
, . ,
,
.
1.3.2.
. 5 .
, .
, , ,
(. 7).
. 7.
. . , , , ( 5).
17
5
BDTur_firm.mdb
5
6
MEMO
/
/
.
, , .
1.3.3.
.
(
\ ).
.
, .
18
,
(. 8).
. 8.
,
,
, (. 9).
. 9.
:
,
. .
. 10.
, -. , .
-- --. --
,
.
-- , : ,
.
,
(. 11).
. . +
,
. ,
.
20
. 11. BDTur_firm.mdb
. 12 . , .
. 12.
(. 13).
21
. 13.
Microsoft
Access, .
: , .
, -. Microsoft Access
(, , ).
Microsoft Access
. ( 255)
- . , , Microsoft SQL Server.
1.4.1.
Microsoft SQL Server Management Studio
Express . 14.
.
. 15.
. 15.
23
,
, .
(. 16).
Microsoft SQL
nvarchar
ntext
int
Microsoft SQL
4000
30
Unicode 2 1 (1 073 741 823)
()
31
2 (2 147 483 648)
31
2 1 (+2 147 483 647)
24
Microsoft Access
4 /
Microsoft SQL
smalldatetime
money
6
7
int
bit
OLE
image
9
10
ntext
nvarchar
6
Microsoft SQL
1 1900 . 6
2079
,
63
2 (922 337 203 685 477.5808)
63
2 1 (+922 337 203 685 477.5807),
. 3
,
0 1
31
0 2 1 (2 147 483 647)
. 2
. 1
. Management Studio (. 17).
.
(. 18).
. 18.
, .
, Management Studio (. 19).
. 19.
26
. (. 20).
. 20.
INSERT UPDATE,
.
(. 21).
Microsoft Access, ,
,
. .
, . , SQL
Management Studio, Access,
(. 22).
, .
27
. 21. BDTur_firmSQL
. 22.
. 23.
. , , .
.
SQL
Management Studio, (. 24).
BDTur_firmSQL.mdf .
. , .
29
. 24.
1.5. 1
1.
: ? ?
2. [ABC]:
(, , ), (1, , ), (1, 1, ), (2, , 1), (, , ), (1, , 1), (2, 1, )? ?
3. [, ,
, , ], ,
, ,
, ,
. . ?
4. :
a. , ;
b. ;
c. ;
d. ;
e. ;
f. , , ;
g. , .
30
h. 10% .
i. , , 12 000 .,
, , 2 .
j. 18 000 . 21 780.
k. 16 000 ., 3 .
l. 20 000 . 2 ,
.
, . 3,
.
5. [ ,
, , , ], ,
, , , ,
.
6. ?
7. ,
, ?
8. [A1, A2, .., AN]?
?
9. 3,4.
10. -
, .
11. [, , _,
, , , , , ],
:
a. , _, , ,
;
b. _;
c. .
3.
12. - , ,
.
31
2. SQL
,
. , ,
, , , .
SQL (Structured Query Language), ,
,
. SQL ANSI ( ), ISO ( ).
SQL, , , , . .
, SQL. , , ,
.
,
, ( )
.
, , . ,
.
SQL- SQL Management Studio. Management Studio
(. 25).
. 25.
32
. 26.
, , . SQL Management
Studio , (. 27).
, , , .
2.1. SQL-
SQL
:
Select < >
From < >
Where <>
, . , , where.
33
.
, , ,
where.
, F5 (
):
select * from ;
BDTur_firmSQL.
(. 27).
. 27.
.
,
:
select from ;
28.
34
(. 29):
select top 3 from ;
. 29.
.
. 28.
,
. ,
, , .
order by,
,
asc ( ), dec (
). :
select top 3 from order by asc;
percent,
:
select top 25 percent from ;
30.
. 30.
, , where:
select * from where > 27000;
,
, 27000 (. 31).
. 31.
35
. 32.
. 33.
2.2. SQL
, ,
, . . , .
(, , , . .)
. () .
group by.
.
count .
36
sum
.
avg ()
.
max .
min .
select count (*) from ;
34.
. 34.
, count
,
.
( - ),
:
select , count () from group by ;
, ,
( ,
count, ).
select sum() from
select avg() from
select max() from
select min() from
, null. , null
, 0 () . :
1) Microsoft SQL Server null,
null;
2) null.
2.3. like
like . ,
.
37
, , ,
,
, .
. 35. like
select , , from
where Like '%'
, 35.
like , ( 7).
7
like
like '5[%]'
like '[_]n'
like '[acdf]'
like '[acdf]'
like '[ [ ]'
like ']'
like 'abc[_]d%'
like 'abc[def]'
5%
_n
a, b, c, d, f
, a, c, d, f
[
]
abc_d abc_de
abcd, abce, abcf
2.4. SQL
SQL
, , - . ,
( ) ,
. SQL, DML (Data Manipulation Language, ). SQL, DDL (Data
Definition Language, ), .
create table.
. create table , , ,
. , . ,
, .
create table:
create table ClientInfo (
FirstName varchar(20), LastName varchar(20), Address varchar(20), Phone varchar(15)
);
38
varchar Unicode.
, ,
1 8000. , ,
. :
.
Management Studio
(. 36).
, ,
varchar,
20
, 15.
Null.
Management Studio,
.
. 36.
2.5. DML
DML ( ):
insert (),
update (),
delete ().
insert .
1) DEFAULT.
2) ,
NULL.
3) .
4) NULL , DEFAULT.
:
insert into ClientInfo (FirstName, LastName, Address, Phone)
values('Petr','Petrov','Chehova 13','1234567');
39
( F5 )
. , values:
insert into ClientInfo (FirstName, LastName, Address, Phone)
values('Ivan','Ivanov','Naberejnaya 13','1234568');
insert into ClientInfo (FirstName, LastName, Address, Phone)
values(null,'Sidorov','Naberejnaya 25','1234569');
(. 37):
select * from ClientInfo;
. 37. ClientInfo
, null,
null.
update :
update ClientInfo set FirstName = 'Andrey' where FirstName = 'Petr';
FirstName Petr
Andrey (. 38).
. 38.
, , , , update .
delete .
delete from ClientInfo where LastName like 'Petrov';
ClientInfo.
, ,
, .
insert, update delete
SQL.
40
2.6. 2
1. SQL-
( , . . 2.1. select * from ;).
2. . 1 .
3. :
select , , from order by dec, asc; ?
4. SQL-, , . .
5. .
6. ? , ,
.
7. , (,
)?
8.
SQL-: update set = ''?
9. SQL-:
delete from where like ''?
10. SQL-:
delete from ?
11. SQL- ,
? .
12. .
13. update SQL-
.
14. .
15. , .
16. .12 1.5.
SQL-, , .
17. ClientInfo.
18. SQL :
select * from where in ('', '');
select * from order by [ ] dec;
update ClientInfo set FirstName = 'Andrey' where FirstName = NULL;
41
3.
3.1.
,
Microsoft Access.
Windows-1.
392.
(Data)
. 39.
39 (Data),
.
Binding Source.
.
(. 40).
- - , Ctrl+Shift+N, .
2
MS Visual C# 2008, ,
, . ,
, .
42
Binding Source
, .
DataSource, .
, .
(. 41).
. 41.
43
. 42.
:
Database ;
Service , , .
Web-;
Object ,
.
(Database).
(. 43).
44
. 43.
,
ADO,
, , , .
. ,
(New connection).
(. 44).
(
Microsoft Access), (
), , . (Advanced)
,
ADO. (Test Connection)
.
.
.
45
. 44.
, . 45.
. 45.
46
.
, , , 45 .
. (Finish)
BindingSource DataSet.
, , .
DataGridView Data.
(. 46).
. 46. DataGridView
,
: (Enable Adding), (Enable Editing),
(Enable Deleting); :
(Enable Column Reordering); -.
,
.
(. 47).
47
. 47. DataGridView
.
(. 48).
. 48. DataGridView
, BindingSource TableAdapter, . ,
design-time .
48
.
DataGridView (. 49).
. 49. DataGridView
, (Binding Source)
. ,
.
.
50.
. 50.
49
.
BindingNavigator. (. 51).
. 51. BindingNavigator
, .
,
ToolStripContainer.
, , ,
BindingSource.
BindingSource.
(. 52).
. 52. BindingNavigator
DataGridView , . ,
. , TextBox .
Panel, TextBox (. 53).
50
. 53.
TextBox .
DataBindings Advanced, 54.
,
55. ,
,
, .
TextBox Binding
BindingSource .
TextBox
.
(. 56).
51
. 56.
. , , , . , DataSet,
. .
52
, Update
TableAdapter. , Click
:
TableAdapter.Update(bDTur_firmDataSet);
__TableAdapter.Update(bDTur_firmDataSet);
, . ,
, , .
3.2.3. DataRelation
DataSet Relations,
DataRelationCollection, DataRelation.
DataRelation (
- ()). ,
DataColumn.
3.2.4. ( DataRow)
Rows DataTable () .
53
. .
3.2.5. DataAdapter
DataSet , . DataSet DataAdapter.
, , . DataAdapter
Fill() DataSet.
54
(Server Explorer) .
(Retrieve
Data) (. 59).
. 59.
.
.
55
3.4.
, , (. . 3.1).
, , :
Microsoft Access BDTur_firm.mdb (. . 1.3);
Microsoft SQL BDTur_firmSQL.mdf (. . 1.4).
Visual Studio 2008 Windows
Application.
DataGridView, Dock Fill. :
MS Access using System.Data.OleDb;
MS SQL using System.Data.SqlClient;
System.Data.
InitializeComponent DataAdapter.
, MS Access,
:
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
OleDbDataAdapter dataAdapter =
new OleDbDataAdapter(CommandText, ConnectionString);
}
, MS SQL:
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
SqlDataAdapter dataAdapter =
new SqlDataAdapter(CommandText, ConnectionString);
}
, .
DataAdapter
CommandText
SQL- ,
onnectionString , , , .
:
// MS Access
CommandText: "SELECT [ ], , , FROM ";
ConnectionString: "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="D:\\For ADO\
BDTur_firm.mdb"
// MS SQL:
CommandText: "SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address,
City, Region, PostalCode, Country, Phone, Fax FROM Customers"
ConnectionString: Data Source=.\SQLEXPRESS;AttachDbFilename="D:\\For ADO\
BDTur_firmSQL.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True
CommandText
, Fill. , .
, .
3.5. 3
1. , . 3.1, .
2. UML- .
3.
ConnectionString
CommandText?
13. . 3.1
(. . 1.5, 4).
14. .
15. (. . 1.5, 11). . 3.1 .
16.
.
58
4. ADO .NET
4.1.
4.1.1. ConnectionString
ConnectionString ,
.
, ( ) .
, BDTur_firm.mdb BDTur_firmSQL.mdf.
// BDTur_firm:
Provider=Microsoft.Jet.OLEDB.4.0;
Data Source="D:\\For ADO\BDTur_firm.mdb" //
// NorthwindCS:
Data Source=.\SQLEXPRESS;
AttachDbFilename="D:\\For ADO\ BDTur_firmSQL.mdf";
Integrated Security=True;
Connect Timeout=30;
User Instance=True
. 8 .
8
Provider ()
, OleDbConnection
Connection Timeout
Connect Timeout
( ) . 15
Initial Catalog
( )
Data Source
SQL-, ( )
, Microsoft Access
Password ()
SQL Server
User ID
SQL Server
( ID)
Workstation ID
59
Integrated Security
Trusted Connection
( , )
Persist Security Info
(
)
4.1.2. . Connection
. , , MS Access 255 .
, ,
.
, .
DataAdapter (, Fill),
, . , DataAdapter , .
:
;
;
.
Connection.
, , DataGridView, Dock
Fill. :
using System.Data.OleDb;
Form1 InitializeComponent Connection:
OleDbConnection conn = new OleDbConnection(ConnectionString);
conn
ConnectionString.
onn:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnectionString;
60
, (. . 3.4). ,
string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=D:\\For ADO\BDTur_firm.mdb";
, Open
Connection:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnectionString;
conn.Open();
4.1.3. Connection
Connection , . 9.
9
Connection
Disposed
InfoMessage
StateChange
Dispose
Dispose Connection
.
Close.
Windows-,
BDTur_firmSQL.mdf.
dataGridView Dock=Top,
btnFill , (
Label). AutoSize False, Dock
(label2) Top, Dock (label1) None, , (. 61).
Form1.cs:
using System.Data.SqlClient;
connectionString commandText:
string connectionString = @"Data Source=.\SQLEXPRESS; AttachDbFilename=" +
@"D:\\For ADO\BDTur_firmSQL.mdf" +
";Integrated Security=True;Connect Timeout=30";
string commandText = "SELECT * FROM ";
61
ADO Click :
private void btnFill_Click(object sender, System.EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connectionString;
// EventHandler - conn_Disposed
// Disposed conn
conn.Disposed+=new EventHandler(conn_Disposed);
// StateChangeEventHandler - conn_StateChange
// StateChange conn
conn.StateChange+= new StateChangeEventHandler(conn_StateChange);
SqlDataAdapter dataAdapter = new SqlDataAdapter(commandText, conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGrid1.DataSource = ds.Tables[0].DefaultView;
// Dispose, Close,
// .
conn.Dispose();
}
- TAB
. 60.
conn_Disposed
label2:
private void conn_Disposed(object sender, EventArgs e)
{
label2.Text+=" Dispose";
}
.
conn_StateChange :
private void conn_StateChange(object sender, StateChangeEventArgs e)
{
label1.Text+="\n : "+e.OriginalState.ToString() +
"\n : "+ e.CurrentState.ToString();
}
. conn
(Closed).
Open, Closed. , (. 61). ( Dispose)
(Closed),
(Open). , .
62
. 60. - Intelligence
. 61.
63
, . , , .
4.1.4.
MS SQL
.
.
.
Microsoft SQL Server
SqlException SqlError. , ( 10).
10
SQL Server
17
4060
18456
1116
1719
2025
64
,
.
SqlException. Errors,
SqlError. Number, . , , .
MS Access
MS
Access OleDbException.
Errors. :
1) Message . MS Access, . . , .
2) NativeError ( ) ,
.
SQL State , , .
4.1.5.
, , , ,
.
, Close,
:
.
, .
(. 62, ). ,
, , 60 .
(. 62, ). , , 35 , , ,
(. 62, ).
65
. 62.
,
,
. . , , , .
.NET
. Close
, . 60 , ,
. -
, , onnectionString
.
66
OLE DB:
SQL Server:
OLE DB Services=4;
Pooling=False;
Close .
Microsoft SQL Server ( 12).
12
MS SQL Server
Connection
Lifetime
( ), .
. , ,
, , . 0 , (60 .)
.
Enlist
Max Pool Size
True
100
0
True
, ,
ConnectionString.
, ,
. .
4.2.
SQL-,
.
.
SQL- 67
- . , .
. . ,
,
.
4.2.1.
Management Studio SQL-,
:
exec sp_databases
, (. 63):
,
master. (Stored Procedures) .
sp. ,
.
:
exec sp_monitor
SQL-
(. 64).
68
Northwind3
:
USE Northwind
exec sp_stored_procedures
Northwind 1312 (. 67),
. .
. 65. Northwind
69
4.2.2.
.
:
create procedure proc1 as
select [ ], , , from
create procedure ,
, proc1 , as
SQL-. , . :
.
The COMMAND(s) completed successfully.
, proc1. , Management Express (. 66)4.
. 66.
:
exec proc1
(. 67).
,
SQL-.
13 .
Management Express ( , F5).
70
. 67. proc1
13
SQL-
exec proc1
exec proc2
exec proc3
71
SQL-
exec proc4
13
72
exec proc5
exec proc6
exec proc7
exec proc8
,
( )
SQL-
exec proc9
13
10
exec proc10
,
BDTur_firm
.
6 ,
5.
() , () . :
from 1 left join 2
on 1.1 < > 2.2.
4.2.3.
() .
, .
, :
create proc proc_p1
@ nvarchar(50)
as
select *
from
where =@
@ . ,
nvarchar c 50, .
exec proc_p1 .
:
exec proc_p1 ''
,
(. 68).
. 68. proc_p1
, ,
, .
14 .
74
14
75
SQL-
create proc proc_p1
exec proc_p1 ''
@ nvarchar(50)
as
select *
from
where =@
SQL-
create proc proc_p2
exec proc_p2 ''
@nameTour nvarchar(50)
as
select *
from
where =@nameTour
SQL-
create procedure proc_p3
exec proc_p3 ''
@ nvarchar(50)
as
select *
from inner
join [ ]
on .[ ] =
[ ].[ ]
where . = @
SQL-
create procedure proc_p4
@nameTour nvarchar(50)
as
select *
from inner join
on .[ ]=.[ ]
where . = @nameTour
14
exec proc_p4 ''
( )
SQL-
create proc proc_p5
@nameTour nvarchar(50),
@ float
as update set
=/(@)
where =@nameTour
exec proc_p5 '', 26
exec proc_p5
@nameTour = '',
@= 26
SQL :
select * from
.
. update, ,
select
(1 )
select
76
14
exec proc_p6 ''
SQL-
create proc proc_p6
@nameTour nvarchar(50),
@ float = 26
as update set
=/(@)
where =@nameTour
, @
.
.
:
exec proc_p6 ''
select:
,
SQL- . ,
( ). :
create proc proc_po1
@TouristID int,
@LastName nvarchar(60) output
as
select @LastName = from where [ ] = @TouristID
output ,
@LastName. ,
4:
declare @LastName nvarchar(60)
exec proc_po1 '4',
@LastName output
select @LastName
declare ,
. (. 69):
77
. 69.
proc_po1
. 70.
proc_po1.
:
declare @LastName nvarchar(60)
exec proc_po1 '4',
@LastName output
select @LastName as ' '
(. 70).
15 .
15
SQL-
1 create proc proc_po1
declare @LastName nvarchar(60)
@TouristID int,
exec proc_po1 '4',
@LastName nvarchar(60) output as
@LastName output
select @LastName =
select @LastName as
from
' '
where [ ] = @TouristID
SQL-
2 create proc proc_po2
declare @CountCity
@CountCity int output as select
int exec proc_po2 @CountCity
@CountCity = count([ ])
output select @CountCity
from [ ]
as ' , where like '%%'
%%'
,
. (, ,
)
78
SQL-
15
SQL
3 create proc proc_po3
declare @CountTour int
@TouristID int,
exec proc_po3 '1', @CountTour output
@CountTour int output
select @CountTour
as select
AS ' , @CountTour = count(.[ ])
'
from inner join on
.[ ]=
.[ ]
inner join on
.[ ] = .[ ]
inner join on
.[ ] =
.[ ]
where .[ ] =
@TouristID
SQL
4 create proc proc_po4
@TouristID int,
@BeginDate smalldatetime,
@EndDate smalldatetime,
@SumMoney money output
as select @SumMoney = sum()
from inner join on
.[ ] =
.[ ]
inner join on
.[ ] =
.[ ]
where [ ]
between(@BeginDate)
and (@EndDate)
and .[ ] =
@TouristID
79
declare
@TouristID int,
@BeginDate smalldatetime,
@EndDate smalldatetime,
@SumMoney money
exec proc_po4 '1',
'1/20/2007',
'1/20/2008',
@SumMoney output
select @SumMoney
as ' '
15
SQL-
, . 1 4/13/2007
SQL
5 create proc proc_po5
@CodeTour int,
@ChisloPutevok int output as
select @ChisloPutevok =
count(.[ ])
from inner join on
.[ ] =
.[ ]
inner join on .[ ] =
.[ ]
where .[ ] = @CodeTour
declare @ChisloPutevok
int exec proc_po5 '1',
@ChisloPutevok output
select @ChisloPutevok
AS ' ,
'
drop:
drop proc proc1
proc1 (. . 13 1).
81
. 71.
. 72.
Server Explorer
82
, :
CREATE PROCEDURE dbo.StoredProcedure1
/*
(
@parameter1 int = 5,
@parameter2 datatype OUTPUT
)
*/
AS
/* SET NOCOUNT ON */
RETURN
,
/*, */.
NOCOUNT ON , .
,
(SELECT, INSERT, UPDATE DELETE) SET NOCOUNT ON, SELECT SET NOCOUNT OFF.
, proc_po1 (. 15) :
CREATE PROCEDURE dbo.proc_vs1
@TouristID int,
@LastName nvarchar(60) OUTPUT
)
AS
SET NOCOUNT ON
SELECT @LastName =
FROM
WHERE ([ ] = @TouristID)
RETURN
SQL- .
SQL (Design SQL Block),
(Query Builder) (. 73).
,
74, Execute.
83
, .
. , "proc_vs1" .
,
:
ALTER PROCEDURE dbo.proc_vs1
ALTER
() .
. 74.
84
4.3.
4.3.1. SQL- CommandText
SQL-. , CommandText
SQL-,
.
,
CommandText. , , SQL- :
string CommandText = "SELECT , , FROM ";
(. 75).
. 75.
, "":
string CommandText = "SELECT , ,
FROM where like '%'";
76.
85
. 76.
(DML) SQL CommandText .
4.3.2. Command
ADO .NET DataAdapter ,
, .
,
, , ADO .NET , Command. SQL- .
InitializeComponent. .
Connection . , .
CommandType (),
. :
Text. SQL-, . .
StoredProcedure. .
TableDirect. .
.
SELECT * FROM _. OLE DB.
CommandText .
, Connection Command
Connection:
86
// , Connection
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnectionString; // . 4.1
conn.Open();
// Command Connection
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = conn;
Connection CreateCommand,
Command,
Connection:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnectionString;
conn.Open();
OleDbCommand myCommand = conn.CreateCommand();
Command . SQL-, .
, .
myommand
CommandText. ,
CommandText commandText ( ):
MyCommand.CommandText = commandText;
OleDbDataAdapter:
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
dataAdapter SelectCommand,
myCommand:
dataAdapter.SelectCommand = myCommand;
DataSet:
DataSet ds = new DataSet();
ds dataAdapter:
dataAdapter.Fill(ds, "");
DataSource dataGrid1:
dataGrid1.DataSource = ds.Tables[""].DefaultView;
:
conn.Close();
. , 60, , ,
.
87
:
public Form1()
{
InitializeComponent();
string commandText = "SELECT , , FROM ";
string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=D:\\For ADO\BDTur_firm.mdb";
OleDbConnection conn=new OleDbConnection(ConnectionString);
conn.Open();
OleDbCommand MyCommand=new OleDbCommand();
MyCommand.Connection = conn;
// OleDbCommand MyCommand=conn.CreateCommand();
MyCommand.CommandText = commandText;
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
dataAdapter.SelectCommand = MyCommand;
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "");
dataGridView1.DataSource = ds.Tables[""].DefaultView;
conn.Close();
}
SQL .
OleDbConnection,
OleDbCommand, OleDbDataAdapter SqlConnection, SqlCommand, SqlDataAdapter
.
, ( ) ADO .
. , ,
(, Web-) ADO .
,
TextBox, Label .
(. . 3.1).
CommandType CommandText
Windows-
. DataGridView, Dock Fill. connectionString commandText:
private string connectionString = @"Data Source = .\SQLEXPRESS; AttachDbFilename = " +
@"D:\\For ADO\BDTur_firmSQL2.mdf" +
";Integrated Security=True; Connect Timeout=30; User Instance=True";
88
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename="+
@"D:\\For ADO\BDTur_firmSQL2.mdf" +
";Integrated Security=True;Connect Timeout=30;User Instance=True";
string commandText = "SELECT * FROM ";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand myCommand = conn.CreateCommand();
myCommand.CommandText = "UPDATE " +
"SET = '' WHERE [ ] = 3";
myCommand.ExecuteNonQuery();
conn.Close();
}
}
}
CommandText ,
= 3.
ExecuteNonQuery:
myCommand.ExecuteNonQuery();
, F5.
. Management Studio, ,
(. 77).
. 77. ,
90
ExecuteNonQuery
.
, , :
int UspeshnoeIzmenenie = myCommand.ExecuteNonQuery();
if (UspeshnoeIzmenenie !=0)
{
Console.WriteLine (" ");
else
{
Console.WriteLine(" ");
,
.
CommandText :
myCommand.CommandText =
"INSERT " +
"INTO ([ ], , , ) " +
"VALUES (6, '', '', '')";
, SQL Server Enterprise Manager
(. 78).
. 78. ,
CommandText,
:
myCommand.CommandText = "DELETE FROM WHERE [ ] = 4";
(. 79).
ExecuteNonQuery , DDL SQL. (Data Defi91
. 79. ,
CommandText ,
BDTur_firm2 :
myCommand.CommandText = "CREATE TABLE ( INT NOT NULL, " +
" INT NOT NULL, VARCHAR(50))";
, Management Studio,
() (. 80).
. 80. ""
. 81. BDTur_firm2,
.. ""
CommandText
:
myCommand.CommandText = "ALTER TABLE ADD VARCHAR(50)";
Management Studio (. 81).
92
,
CommandText:
myCommand.CommandText = "DROP TABLE ";
Management Studio , . , , :
myCommand.CommandText = "DELETE FROM ";
,
, , .
DDL.
ExecuteNonQuery ,
DCL. (Data Control Language, DCL) ( )
.
GRANT, DENY, REVOKE. Commnad .
ExecuteScalar
ExecuteScalar Command , . COUNT, MIN, MAX. . :
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename="+
@"D:\\For ADO\BDTur_firmSQL2.mdf"+
";Integrated Security=True;Connect Timeout=30;User Instance=True";
string commandText = "SELECT * FROM ";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand myCommand = conn.CreateCommand();
myCommand.CommandText = "SELECT COUNT (*) FROM ";
string KolichestvoTurov = Convert.ToString(myCommand.ExecuteScalar());
93
conn.Close();
Console.WriteLine(" : " + KolichestvoTurov);
Console.ReadKey();
}
}
}
ExecuteScalar string
. 5
(. 82).
. 82.
.
myCommand.CommandText = "SELECT COUNT (*) FROM ";
string KolichestvoTurov = Convert.ToString(myCommand.ExecuteScalar());
myCommand.CommandText = "SELECT MAX () FROM ";
string MaxPrice = Convert.ToString(myCommand.ExecuteScalar());
myCommand.CommandText = "SELECT MIN () FROM ";
string MinPrice = Convert.ToString(myCommand.ExecuteScalar());
myCommand.CommandText = "SELECT AVG () FROM ";
string AvgPrice = Convert.ToString(myCommand.ExecuteScalar());
conn.Close();
Console.WriteLine(" : " + KolichestvoTurov +
"\n , . : " + MaxPrice +
"\n , .: " + MinPrice +
"\n : " + AvgPrice);
(. 83).
. 83.
,
ExecuteScalar.
.
94
ExecuteReader
ExecuteReader.
. , DataReader, . ,
, DataSet. DataReader,
DataSet, , , .
. :
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename="+
@"D:\\For ADO\BDTur_firmSQL2.mdf"+
";Integrated Security=True;Connect Timeout=30;User Instance=True";
string commandText = "SELECT * FROM ";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand myCommand = conn.CreateCommand();
myCommand.CommandText = "SELECT * FROM ";
SqlDataReader dataReader = myCommand.ExecuteReader();
while (dataReader.Read())
{
Console.WriteLine(dataReader[""]);
}
dataReader.Close();
conn.Close();
Console.ReadKey();
}
}
}
dataReader ExecuteReader
myCommand:
SqlDataReader dataReader = myCommand.ExecuteReader();
95
Read dataReader .
84.
. 84.
DataReader object,
:
Console.WriteLine(dataReader[1]);
:
Console.WriteLine(dataReader[0]);
Console.WriteLine(dataReader[1]);
Console.WriteLine(dataReader[2]);
Console.WriteLine(dataReader[3]);
(. 85).
. 85.
( object),
:
...
Console.WriteLine(dataReader[0] + dataReader[1] + dataReader[2] + dataReader[3]);
...
96
string :
Console.WriteLine(Convert.ToString(dataReader[0]) + " " +
Convert.ToString(dataReader[1]) + " " +
Convert.ToString(dataReader[2]) +" " +
Convert.ToString(dataReader[3]));
(. 86).
. 86.
4.3.3.
Command . ,
- . ,
, ? , , ,
. , , , .
, ,
. ,
ExecuteNonQuery commandText :
myCommand.CommandText =
"UPDATE SET = '' WHERE = 3";
,
, , . :
myCommand.CommandText = " UPDATE SET
= '-_,___'
WHERE = '-_,___' ";
, SQL, . :
myCommand.CommandText =
"UPDATE SET = @Family WHERE = @TouristID";
97
@Family ,
@TouristID . ,
.
,
.
ExecuteNonQuery
Windows .
(. 87).
. 87. ,
:
using System.Data.SqlClient;
conn:
SqlConnection conn = null;
btnUpdate :
private void btnUpdate_Click(object sender, System.EventArgs e)
{
try
{
string Family = Convert.ToString(this.txtFamilyUpdate.Text);
int TouristID = int.Parse(this.txtTouristIDUpdate.Text);
conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" +
@"D:\\For ADO\BDTur_firmSQL2.mdf" +
";Integrated Security=True;Connect Timeout=30;User Instance=True";
conn.Open();
98
99
16
Add
parameterName
sqlDbType
size
sourceColumn
DataSet,
btnInsert.
private void btnInsert_Click(object sender, System.EventArgs e)
{
try
{
int TouristID = int.Parse(this.txtTouristIDInsert.Text);
string Family = Convert.ToString(this.txtFamilyInsert.Text);
string FirstName = Convert.ToString(this.txtFirstNameInsert.Text);
string MiddleName = Convert.ToString(this.txtMiddleNameInsert.Text);
conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" +
@"D:\\For ADO\BDTur_firmSQL2.mdf" +
";Integrated Security=True;Connect Timeout=30;User Instance=True";
conn.Open();
SqlCommand myCommand = conn.CreateCommand();
myCommand.CommandText = "INSERT INTO " +
" ([ ], , , ) " +
"VALUES (@TouristID, @Family, @FirstName, @MiddleName)";
myCommand.Parameters.Add("@TouristID", SqlDbType.Int, 4);
myCommand.Parameters["@TouristID"].Value = TouristID;
myCommand.Parameters.Add("@Family", SqlDbType.NVarChar, 50);
myCommand.Parameters["@Family"].Value = Family;
myCommand.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50);
myCommand.Parameters["@FirstName"].Value = FirstName;
myCommand.Parameters.Add("@MiddleName", SqlDbType.NVarChar, 50);
myCommand.Parameters["@MiddleName"].Value = MiddleName;
int UspeshnoeIzmenenie = myCommand.ExecuteNonQuery();
if (UspeshnoeIzmenenie !=0)
{
MessageBox.Show(" ", " ");
}
else
{
100
: @TouristID, @Family,
@FirstName, @MiddleName.
.
btnDelete.
private void btnDelete_Click(object sender, System.EventArgs e)
{
try
{
int TouristID = int.Parse(this.txtTouristIDDelete.Text);
conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" +
@"D:\\For ADO\BDTur_firmSQL2.mdf" +
";Integrated Security=True;Connect Timeout=30;User Instance=True";
conn.Open();
SqlCommand myCommand = conn.CreateCommand();
myCommand.CommandText = "DELETE FROM " +
"WHERE [ ] = @TouristID";
myCommand.Parameters.Add("@TouristID", SqlDbType.Int, 4);
myCommand.Parameters["@TouristID"].Value = TouristID;
int UspeshnoeIzmenenie = myCommand.ExecuteNonQuery();
if (UspeshnoeIzmenenie !=0)
{
MessageBox.Show(" ", " ");
}
else
{
101
. 88.
102
. 89.
. 90.
103
ExecuteScalar
ExecuteScalar Command Windows-
( , )
.
ExecuteReader
ExecuteReader. .
. ListBox,
Dock Bottom. Splitter,
Dock Bottom. , ListView, Dock Fill.
, ListView: Properties
(...).
Columns
Column Header Collection Editor :
Name
Text
chTouristID
chFamily
chFirstName
chMiddleName
View Details.
GridLines True.
.
:
using System.Data.SqlClient;
conn dataReader:
SqlConnection conn = null;
SqlDataReader dataReader;
:
public Form1()
{
InitializeComponent();
try
{
conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" +
@"D:\\For ADO\BDTur_firmSQL2.mdf" +
";Integrated Security=True;Connect Timeout=30;User Instance=True";
104
conn.Open();
SqlCommand myCommand = conn.CreateCommand();
myCommand.CommandText = "SELECT * FROM ";
dataReader = myCommand.ExecuteReader();
while (dataReader.Read())
{
// , dataReader,
// Get
int TouristID = dataReader.GetInt32(0);
string Family = dataReader.GetString(1);
string FirstName = dataReader.GetString(2);
string MiddleName = dataReader.GetString(3);
// listBox1
listBox1.Items.Add(" : " + TouristID+ " : " + Family +
" : "+ FirstName + " : " + MiddleName);
// item ListViewItem
// dataReader
ListViewItem item = new ListViewItem(new
string[]{Convert.ToString(dataReader[0]), Convert.ToString(dataReader[1]),
Convert.ToString(dataReader[2]), Convert.ToString(dataReader[3])});
listView1.Items.Add(item);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
dataReader.Close();
conn.Close();
}
}
Get , DataReader, .
. ListBox ListView (. 91).
ListView ,
DataGridView. , DataSet,
DataGridView :
dataGridView1.DataSource = dataset.Tables["_"].DefaultView;
105
:
dataGridView1.DataSource = dataset;
DataReader
:
dataGridView1.DataSource = datareader;
. 91. ExecuteReader
DataTable. DataTable , .
. DataGrid, Dock Fill.
:
using System.Data.SqlClient;
:
SqlConnection conn = null;
// FullDataTable,
DataTable FullDataTable = new DataTable();
// FullDataTable
DataTable ShemaDataTable = new DataTable();
SqlDataReader dataReader;
SqlCommand myCommand;
// objectRow
object[] objectRow;
// myDataRow
DataRow myDataRow;
:
106
public Form1()
InitializeComponent();
try
{
conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" +
@"D:\\For ADO\BDTur_firmSQL2.mdf" +
";Integrated Security=True;Connect Timeout=30;User Instance=True";
conn.Open();
myCommand = conn.CreateCommand();
myCommand.CommandText = "SELECT * FROM ";
dataReader = myCommand.ExecuteReader();
// GetSchemaTable,
// ShemaDataTable
ShemaDataTable = dataReader.GetSchemaTable();
// FieldCount .
// objectRow
objectRow = new object[dataReader.FieldCount];
// FullDataTable
for(int i =0; i <dataReader.FieldCount; i++)
{
FullDataTable.Columns.Add(ShemaDataTable.Rows[i]["ColumnName"].ToString(),
((System.Type)ShemaDataTable.Rows[i]["DataType"]));
}
// FullDataTable
while(dataReader.Read())
{
dataReader.GetValues(objectRow);
myDataRow = FullDataTable.Rows.Add(objectRow);
}
// dataGrid1
dataGrid1.DataSource = FullDataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
dataReader.Close();
conn.Close();
}
}
107
(. 92):
. 92.
4.3.4.
. ( 13),
, ,
Windows-. ( 14), , .
Windows-, .
93.
:
string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" +
@"D:\\For ADO\BDTur_firmSQL2.mdf" +
";Integrated Security=True;Connect Timeout=30;User Instance=True";
Connection Command,
,
Parameters:
private void btnRun_p1_Click(object sender, System.EventArgs e) {
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connectionString;
SqlCommand myCommand = conn.CreateCommand();
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "[proc_p1]";
string FamilyParameter = Convert.ToString(txtFamily_p1.Text);
108
. 93. proc_p1
110
. 94. proc_p5
. 95. proc_p6
111
(. 15). Windows, 96.
. 96.
Connection:
SqlConnection conn = null;
btnRun :
private void btnRun_Click(object sender, System.EventArgs e)
{
try
{
conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" +
@"D:\\For ADO\BDTur_firmSQL2.mdf" +
";Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlCommand myCommand = conn.CreateCommand();
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "[proc_po1]";
int TouristID = int.Parse(this.txtTouristID.Text);
myCommand.Parameters.Add("@TouristID", SqlDbType.Int, 4);
myCommand.Parameters["@TouristID"].Value = TouristID;
// , .. .
//myCommand.Parameters["@TouristID"].Direction = ParameterDirection.Input;
myCommand.Parameters.Add("@LastName", SqlDbType.NVarChar, 60);
myCommand.Parameters["@LastName"].Direction = ParameterDirection.Output;
conn.Open();
myCommand.ExecuteScalar();
lblFamily.Text = Convert.ToString(myCommand.Parameters["@LastName"].Value);
}
catch (Exception ex)
{ MessageBox.Show(ex.ToString()); }
finally
{ conn.Close(); }
}
112
. 97.
SQL-
SQL-, . , .
proc_NextResult. proc_NextResult
: , :
CREATE PROCEDURE proc_NextResult
AS
SET NOCOUNT ON
SELECT * FROM
SELECT * FROM
RETURN
Windows-.
ListBox, Dock Bottom. Splitter (), Dock
Bottom. , ListBox, Dock Fill.
: ListBox ,
.
:
113
public Form1()
InitializeComponent();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" +
@"D:\\For ADO\BDTur_firmSQL2.mdf" +
";Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlCommand myCommand = conn.CreateCommand();
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "[proc_NextResult]";
conn.Open();
SqlDataReader dataReader = myCommand.ExecuteReader();
while(dataReader.Read())
{
listBox2.Items.Add(dataReader.GetString(1)+" "+dataReader.GetString(2));
}
dataReader.NextResult();
while(dataReader.Read())
{
listBox1.Items.Add(dataReader.GetString(1) +
". : "+dataReader.GetString(3));
}
dataReader.Close();
conn.Close();
}
98.
. 98.
114
4.3.5.
(SQL) , , . , ,
, .
? , BDTur_firm2
. ,
, , , -
, ,
. .
Management Studio, :
INSERT INTO ([ ], , , )
VALUES (8, '', '', '');
INSERT INTO [ ]([ ], [ ], , ,
, )
VALUES (8, 'CA 1234567', '', '', 1234567, 996548);
:
(1 row(s) affected) // ( : 1)
(1 row(s) affected) // ( : 1)
:
INSERT INTO ([ ], , , )
VALUES (8, '', '', '');
INSERT INTO [ ]([ ], [ ], , ,
, )
VALUES (9, 'CA 1234567', '', '', 1234567, 996548);
. , ,
:
2627, 14, 1, 1
Violation of PRIMARY KEY constraint 'PK_'. Cannot insert duplicate key in object
'dbo.'.
The statement has been terminated.
( : 1)
115
:
SELECT * FROM
SELECT * FROM [ ]
(. 99).
, .
. 99.
SQL :
116
BEGIN TRAN
DECLARE @OshibkiTabliciTourists int, @OshibkiTabliciInfoTourists int
INSERT INTO ([ ], , , )
VALUES (8, '', '', '');
SELECT @OshibkiTabliciTourists=@@ERROR
INSERT INTO [ ]([ ], [ ],
, , , )
VALUES (8, 'CA 1234567', '', '', 1234567, 996548);
SELECT @OshibkiTabliciInfoTourists=@@ERROR
IF @OshibkiTabliciTourists=0 AND @OshibkiTabliciInfoTourists=0
COMMIT TRAN
ELSE
ROLLBACK TRAN
BEGIN TRAN.
@OshibkiTabliciTourists, @OshibkiTabliciInfoTourists
. , @@ERROR :
SELECT @OshibkiTabliciTourists=@@ERROR
:
SELECT @OshibkiTabliciInfoTourists=@@ERROR
,
:
IF @OshibkiTabliciTourists=0 AND @OshibkiTabliciInfoTourists=0
( ) COMMIT TRAN.
@OshibkiTabliciTourists
@OshibkiTabliciInfoTourists ,
ROLLBACK TRAN.
:
( : 1)
( : 1)
:
BEGIN TRAN
DECLARE @OshibkiTabliciTourists int, @OshibkiTabliciInfoTourists int
INSERT INTO ([ ], , , )
VALUES (8, '', '', '');
SELECT @OshibkiTabliciTourists=@@ERROR
INSERT INTO [ ]([ ], [ ],
, , , )
117
. 100.
(1 row(s) affected), ,
, SQL-
, .
118
,
, .
ADO .NET
ADO .NET. EasyTransaction. :
.
:
using System;
using System.Data.SqlClient;
namespace EasyTransaction
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" +
@"D:\\For ADO\BDTur_firmSQL2.mdf" +
";Integrated Security=True;Connect Timeout=30;User Instance=True";
conn.Open();
SqlCommand myCommand = conn.CreateCommand();
//
myCommand.Transaction = conn.BeginTransaction(System.Data.IsolationLevel.Serializable);
try
{
myCommand.CommandText =
"INSERT INTO ([ ], , , ) " +
"VALUES (9, '', '', '')";
myCommand.ExecuteNonQuery();
myCommand.CommandText =
"INSERT INTO [ ]" +
" ([ ], [ ], , , , ) " +
"VALUES (9, 'CA 1234567', '', '', 1234567, 996548)";
myCommand.ExecuteNonQuery();
//
myCommand.Transaction.Commit();
Console.WriteLine(" ");
}
catch(Exception ex)
{
119
//
myCommand.Transaction.Rollback();
Console.WriteLine(" : "+ ex.Message);
}
finally
{
conn.Close();
}
} end Main
} end Class
} end namespace
. , (. 101).
. 101. EasyTransaction.
(. 102).
. 102. EasyTransaction.
, , :
//
. EasyTransaction
//
myCommand.Transaction = conn.BeginTransaction();
120
try
{
// ,
//
myCommand.Transaction.Commit();
}
catch(Exception ex)
{
//
myCommand.Transaction.Rollback();
finally
{
//
conn.Close();
}
:
Dirty reads . ,
. (
) , .
Non-repeatable reads . , .
. (, SELECT) .
Phantom reads . , .
, .
, .
:
Read uncommitted. , . .
Read committed. , .
.
121
Repeatable read. , .
, .
, .
Serializable. .
.
Read committed. Microsoft
SQL Server 20055 ,
(. 103).
(Serializable)
, . , (Read uncommitted)
. ,
.
:
SET TRANSACTION ISOLATION LEVEL
READ UNCOMMITTED
READ COMMITTED
REPEATABLE READ
SERIALIZABLE
, , , :
BEGIN TRAN SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
DECLARE @OshibkiTabliciTourists int, @OshibkiTabliciInfoTourists int
...
ROLLBACK TRAN
isolation levels overview
122
ADO .NET :
myCommand.Transaction = conn.BeginTransaction(System.Data.IsolationLevel.Serializable);
(. 104):
Chaos.
,
,
. ,
, ;
Unspecified. ,
,
. 104.
.
.
, .
4.4.
4.4.1. DataSet, DataTable DataColumn
DataSet .
, , , DataSet DataTable. DataSet , DataTable.
( ) ().
DataTable
DataColumn DataRow. DataRelation. , Constraint UniqueConstraint
ForeighKeyConstraint . , .
, .
, . , , :
DataSet = < > = < DataTable>.
DataTable = <>.
123
,
Questions. Add Columns
dtQuestions (. 105).
. 105.
Unique , , ( questID
Questions).
DataTable Variants ( ) :
//C "Variants"
DataTable dtVariants = dsTests.Tables.Add("Variants");
// "Variants"
DataColumn dcID = dtVariants.Columns.Add("id", typeof(Int32));
dcID.Unique = true;
dcID.AutoIncrement = true;
DataColumn dcVariantQuestID = dtVariants.Columns.Add("questID", typeof(Int32));
DataColumn dcVariant = dtVariants.Columns.Add("variant");
DataColumn dcIsRight = dtVariants.Columns.Add("isRight", typeof(Boolean));
AutoIncrement dcID
true. AutoIncrement ()
, Microsoft Access.
.
Questions Variants questID, . questID Questions
dQuestID, Variants
dcVariantQuestID. :
DataRelation drQuestionsVariants = new DataRelation("QuestionsVariants",
dQuestID, dcVariantQuestID);
dsTests.Relations.Add(drQuestionsVariants);
125
126
.
DataTable
AllowDBNull ( null) DataColumn,
, false.
, ,
PrimaryKey. ,
.
UniqueConstraint ForeignKeyConstraint
,
, . Constraint ()
DataTable UniqueConstraint ForeignKeyConstraint.
UniqueConstraint , ,
Questions questID. dQuestID :
DataColumn dQuestID = dtQuestions.Columns.Add("questID", typeof(Int32));
UniqueConstraint, dQuestID,
:
UniqueConstraint UC_dtQuestions = new UniqueConstraint(dQuestID);
dtQuestions.Constraints.Add(UC_dtQuestions);
dQuestID :
dQuestID.Unique = true;
, UniqueConstraint.
Unique, UniqueConstraint
.
ForeignKeyConstraint ,
. ADO
.NET ,
ForeignKeyConstraint :
UpdateRule ;
DeleteRule ;
AcceptRejectRule AcceptChanges
DataTable, .
, AcceptRejectRule,
:
Cascade ;
127
None ;
SetDefault , DefaultValue ;
SetNull Null.
AcceptRejectRule Cascade None.
UpdateRule DeleteRule Cascade,
AcceptRejectRule None.
QuestionsVariants:
ForeignKeyConstraint FK_QuestionsVariants =
new ForeignKeyConstraint(dtQuestions.Columns["questID"],
dtVariants.Columns["questID"]);
dtVariants.Constraints.Add(FK_QuestionsVariants);
, (. 106).
DataTable, ( dtVariants).
. 106. FK_QuestionsVariants
UpdateRule, DeleteRule
AcceptRejectRule , . . Cascade None, . .
,
,
. BDTur_firm.mdb, .
, . 128
, , , . . (), .
ADO .NET DataColumn, . Windows-.
, :
using System.Data.OleDb;
CommandText ConnectionString:
string commandText = "SELECT , [ ], , FROM ";
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
@"D:\\For ADO\BDTur_firm.mdb";
DataGridView:
public Form1()
{
InitializeComponent();
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = conn;
myCommand.CommandText = commandText;
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
dataAdapter.SelectCommand = myCommand;
DataSet dsTours = new DataSet();
DataTable dtTours = dsTours.Tables.Add("");
DataColumn dIDtour = dtTours.Columns.Add(" ", typeof(Int32));
dIDtour.Unique = true;
DataColumn dcName = dtTours.Columns.Add("");
DataColumn dcPrice = dtTours.Columns.Add("", typeof(Decimal));
DataColumn dcInformation = dtTours.Columns.Add("");
conn.Open();
dataAdapter.Fill(dsTours.Tables[""]);
conn.Close();
dataGrid1.DataSource = dsTours.Tables[""].DefaultView;
}
(. 107).
129
. 107.
DataColumn, , dcPrice:
...
DataColumn dcPrice = dtTours.Columns.Add("", typeof(Decimal));
DataColumn dcPriceNDS = dtTours.Columns.Add(" c ", typeof(Decimal));
dcPriceNDS.Expression = "*0.15+";
DataColumn dcPricewithDiscount = dtTours.Columns.Add(" c ",
typof(Decimal));
dcPricewithDiscount.Expression = "*0.10";
...
Expression DataColumn
(. 108).
. 108. ,
Expression , , .
DataSet DataTable
GetChanges, (. 109).
130
. 109. GetChanges
. DataSet, DataTable DataRow
HasErrors, .
:
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
sqlDataAdapter1.Update(dataSet11);
}
catch(Exception ex)
{
if(dataSet11.HasErrors)
{
foreach( DataTable myTable in dataSet11.Tables)
{
if(myTable.HasErrors)
{
foreach(DataRow myRow in myTable.Rows)
{
if(myRow.HasErrors)
{
MessageBox.Show(" #: " +
myRow[" "], myRow.RowError);
foreach(DataColumn myColumn in myRow.GetColumnsInError())
{
MessageBox.Show(myColumn.ColumnName, " ");
}
myRow.ClearErrors();
myRow.RejectChanges();
}
}
}
,
DataTable, DataRow DataColumn. ClearErrors myRow, RejectChanges .
132
4.4.2. DataRow
DataSet ,
DataRow. DataSet , , DataGridView, , ,
.
DataRow, .
.
Windows-.
dtTours , :
public Form1()
{ InitializeComponent();
DataTable dtTours = new DataTable();
DataColumn dIDtour = dtTours.Columns.Add(" ", typeof(Int32));
dIDtour.Unique = true;
DataColumn dcName = dtTours.Columns.Add("");
DataColumn dcPrice = dtTours.Columns.Add("", typeof(Decimal));
DataColumn dcInformation = dtTours.Columns.Add("");
DataView myDataView = new DataView(dtTours);
dataGrid1.DataSource = myDataView;
}
DataGridView, myDataView DataView. DataTable DataView, , , DataTable.DefaultView. , , :
dataGrid1.DataSource = dsTours.Tables[""].DefaultView;
DataTable DataView
, . . (. 110).
. 110.
133
- . myDataView
:
DataRow myRow = dtTours.NewRow();
myRow[" "] = 1;
myRow[""] = "";
myRow[""] = 25000;
myRow[""] =
" ( 7)";
dtTours.Rows.Add(myRow);
(. 111). .
. 111.
:
DataRow myRow2 = dtTours.NewRow();
myRow2[" "] = 2;
myRow2[""] = "";
myRow2[""] = 32000;
myRow2[""] = " ";
dtTours.Rows.Add(myRow2);
, myRow
myRow2, , .
.
:
DataRow myRow = dtTours.NewRow();
myRow[0] = 1;
myRow[1] = "";
myRow[2] = 25000;
myRow[3] = " ( 7)";
dtTours.Rows.Add(myRow);
DataRow myRow2 = dtTours.NewRow();
myRow2[0] = 2;
myRow2[1] = "";
134
myRow2[2] = 32000;
myRow2[3] = " ";
dtTours.Rows.Add(myRow2);
.
ItemArray DataRow, :
DataRow myRow3 = dtTours.NewRow();
myRow3.ItemArray = new object[] { 3, "", 30000, null };
dtTours.Rows.Add(myRow3);
, null, (. 112).
. 112. null
, DataSet, , . ,
( ) .
.
DataGrid:
dataGrid1.DataSource = dsTours.Tables[""].DefaultView;
.
, , , Rows
dtTours , 4,
, BeginEdit ,
,
EndEdit:
DataRow myRow=dtTours.Rows[4];
myRow.BeginEdit();
myRow[" "] = 5;
myRow[""] = "";
myRow[""] = "27000";
myRow[""] = " 15 ";
myRow.EndEdit();
ItemArray:
135
DataRow myRow=dtTours.Rows[4];
myRow.BeginEdit();
myRow.ItemArray = new object[]
{5,"", 27000, null, null, " 15 "};
myRow.EndEdit();
,
, null, , ,
(. 113).
. 113.
DataRow,
, Remove Rows
DataTable:
DataRow myRow2 = dtTours.Rows[0];
dtTours.Rows.Remove(myRow2);
, , , Delete:
myRow2.Delete();
(. 114), DataTable
,
(, ).
. 114. , 0,
136
RowState
, . DataRow
RowState, .
.
, , :
public Form1()
{
InitializeComponent();
DataTable dtTours = new DataTable("");
DataColumn IDtour = new DataColumn(" ", typeof(Int32));
dtTours.Columns.Add(IDtour);
dataGrid1.DataSource = dtTours;
DataRow myRow;
// ,
myRow = dtTours.NewRow();
richTextBox1.Text += Convert.ToString(" : " + myRow.RowState);
// DataTable
dtTours.Rows.Add(myRow);
richTextBox1.Text += Convert.ToString("\n : " + myRow.RowState);
// DataTable
dtTours.AcceptChanges();
richTextBox1.Text += Convert.ToString("\n AcceptChanges: " + myRow.RowState);
//
myRow[" "] = 1;
richTextBox1.Text += Convert.ToString("\n : " + myRow.RowState);
//
myRow.Delete();
richTextBox1.Text += Convert.ToString("\n: " + myRow.RowState);
// DataTable
dtTours.RejectChanges();
richTextBox1.Text += Convert.ToString("\n RejectChanges: " + myRow.RowState);
. myRow
(. 115).
Detached , DataTable.
Added DataTable, . ,
137
, , DataGrid .
AcceptChanges DataTable, , DataRow Unchanged , .
Delete ,
. ,
RejectChanges DataTable Unchanged.
. 115. RowState
RowState ,
. , , .
RowVersion
RowVersion ( DataRow), .
:
Current
Default
Original
Proposed
. DataRow
DataTable:
DataRow myRow;
DataTable dtTours;
,
DataGridView, :
138
public Form1()
{
InitializeComponent();
dtTours = new DataTable("");
DataColumn IDtour = new DataColumn("", typeof(string));
dtTours.Columns.Add(IDtour);
myRow = dtTours.NewRow();
dtTours.Rows.Add(myRow);
myRow[""] = "";
dataGrid1.DataSource = dtTours;
dataGrid1.Enabled = false;
}
TestRowVersion,
RowVersion :
private void TestRowVersion()
{
if(myRow.HasVersion(DataRowVersion.Original))
rtbReport.Text += String.Format(" original: {0}\n",
myRow["", DataRowVersion.Original]);
if(myRow.HasVersion(DataRowVersion.Current))
rtbReport.Text += String.Format(" current: {0}\n",
myRow["", DataRowVersion.Current]);
if(myRow.HasVersion(DataRowVersion.Default))
rtbReport.Text += String.Format(" default: {0}\n",
myRow["", DataRowVersion.Default]);
if(myRow.HasVersion(DataRowVersion.Proposed))
rtbReport.Text += String.Format(" proposed: {0}\n",
myRow["", DataRowVersion.Proposed]);
}
HasVersion , myRow
, . rtbReport .
btnBeginEdit ()
BeginEdit, :
private void btnBeginEdit_Click(object sender, System.EventArgs e)
{
myRow.BeginEdit();
myRow[""] = "";
rtbReport.Text += "BeginEdit\n";
TestRowVersion();
}
139
btnEndEdit :
private void btnEndEdit_Click(object sender, System.EventArgs e)
{
myRow.EndEdit();
rtbReport.Text += "EndEdit\n";
TestRowVersion();
}
btnCancelEdit :
private void btnCancelEdit_Click(object sender, System.EventArgs e)
{
myRow.CancelEdit();
rtbReport.Text += "CancelEdit\n";
TestRowVersion();
}
btnDelete myRow:
private void btnDelete_Click(object sender, System.EventArgs e)
{
myRow.Delete();
rtbReport.Text += " \n";
TestRowVersion();
}
:
private void btnClear_Click(object sender, EventArgs e)
{
this.rtbReport.Text = "";
}
.
Begin Edit ,
. (Default) Proposed, (Current) (. 116).
140
. 116. . 1
. 117. . 2
(. 118).
141
. 118. . 3
. 119. . 4
myRow
(. 120).
142
. 120. . 5
DataTable
DataTable ,
. :
ColumnChanged ;
ColumnChanging
;
RowChanged DataRow ();
RowChanging DataRow;
RowDeleted DataRow;
RowDeleting DataRow.
DataTable:
public Form1()
{
...
dtTours.RowChanging += new DataRowChangeEventHandler(dtTours_RowChanging);
dtTours.RowChanged += new DataRowChangeEventHandler(dtTours_RowChanged);
dtTours.RowDeleting += new DataRowChangeEventHandler(dtTours_RowDeleting);
dtTours.RowDeleted += new DataRowChangeEventHandler(dtTours_RowDeleted);
...
}
:
143
. 121.
, , (RowChanging) (RowDeleting).
144
4.4.3. DataGridView
DataGridView
Microsoft Access BDTur_firm.mdb , . DataGridView , . Windows-.
DataGridView, Dock Fill. :
using System.Data.OleDb;
, OleDbCommand, CommandText:
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = conn;
myCommand.CommandText = commandText;
BDTur_firm.mdb, connectionString commandText:
string commandText = "SELECT [ ], , , FROM ";
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+
@"D:\\For ADO\BDTur_firm.mdb";
string commandText2 =
"SELECT [ ], [ ], , , , " +
"FROM [ ]";
DataAdapter SelectCommand
myCommand, :
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
dataAdapter.SelectCommand = myCommand;
conn.Open();
DataSet:
DataSet ds = new DataSet();
DataSet . TableMappings
DataAdapter :
dataAdapter.TableMappings.Add("Table", "");
dataAdapter.Fill(ds);
OleDbDataAdapter OleDbCommand
:
OleDbCommand myCommand2 = new OleDbCommand();
myCommand2.Connection = conn;
myCommand2.CommandText = commandText2;
145
. 122.
147
+
. (. 123).
. 123.
. , .
, .
(. 124).
. 124.
148
DataGridView
, , ,
.
DataGridView,
.
:
dataGridView1.DataSource = dsview;
dataGridView1.DataMember = ". ";
125.
. 125.
:
dataGridView1.DataMember = ". ";
.
4.4.4. DataView
DataSet ,
, . DataView
, DataSet. ADO .NET,
, .
149
Windows-.
SQL- DataGridView.
. Form_Load:
DataView myDataView = new DataView(bDTur_firmSQL2DataSet.);
myDataView.RowStateFilter = DataViewRowState.Deleted;
dataGridView2.DataSource = myDataView;
, .
DataGridView
(. 126).
. 126.
DataView DataSet
( ) , .
(DataViewRowState.Added)
(DataViewRowState.ModifiedCurrent) :
myDataView.RowStateFilter =
((DataViewRowState)((DataViewRowState.Added | DataViewRowState.ModifiedCurrent)));
RowStateFilter 17.
RowFilter , .
150
17
RowStateFilter DataView
Unchanged
New
Deleted
Current Modified
Original Modified
:
DataView myDataView = new DataView(bDTur_firmSQL2DataSet.);
myDataView.RowFilter = " = ''";
dataGridView2.DataSource = myDataView;
(. 127).
. 127.
Sort
(ascending, ASC) (descending, DESC) .
, DataGridView .
, DataView .
RowFilter, Sort ASC ( . 128):
DataView myDataView = new DataView(bDTur_firmSQL2DataSet.);
151
. 128.
ADO .NET , DataSet, DataTable, . RowFilter
DataView .
Visual Studio 2008 Windows
Forms Control Library (. 129).
130.
. CheckedChanged
CheckBox:
public FindCheckBox()
{
InitializeComponent();
txtColumnValue.Enabled = false;
chbForSearching.CheckedChanged += new
EventHandler(chbForSearching_CheckedChanged);
}
CheckedChanged
CheckBox , CheckBox.
152
. 130.
. 131.
FindCustomers, :
private void FindCustomers()
{
// filteringFields ArrayList
ArrayList filteringFields = new ArrayList();
// fcbCustomerID
if (fcbCustomerID.SearchEnabled)
// filteringFields ColumnValue
filteringFields.Add("CustomerID LIKE \'" + fcbCustomerID.ColumnValue + "%\'");
if (fcbCompanyName.SearchEnabled)
filteringFields.Add("CompanyName LIKE \'" + fcbCompanyName.ColumnValue + "%\'");
if (fcbContactName.SearchEnabled)
filteringFields.Add("ContactName LIKE \'" + fcbContactName.ColumnValue + "%\'");
if (fcbPhone.SearchEnabled)
filteringFields.Add("Phone LIKE \'" + fcbPhone.ColumnValue + "%\'");
string filter = "";
// .
// ""
if (filteringFields.Count == 1)
filter = filteringFields[0].ToString();
155
. 132.
156
: (. 133).
. 133.
4.4.5.
HashTable
Hashtable ,
. , . Hashtable ,
: . (Keys), (Values) object, ,
int, object!
. :
using System;
using System.Collections;
namespace HashtableExample
{ class Statistics
{ public Hashtable AbonentList;
public Statistics()
{
AbonentList = new Hashtable();
}
}
157
class Abonent
{
public string Name;
public int Phone;
public Abonent(string n, int p)
{
Name = n; Phone = p;
}
}
class Class1
{ [STAThread]
static void Main(string[] args)
{ Abonent a1 = new Abonent("", 1234567);
Abonent a2 = new Abonent("", 3216547);
Abonent a3 = new Abonent("", 685472);
Abonent a4 = new Abonent("", 1234500);
Abonent a5 = new Abonent("", 3245637);
Statistics myStatistics = new Statistics();
myStatistics.AbonentList.Add(a1.Phone, a1.Name);
myStatistics.AbonentList.Add(a2.Phone, a2.Name);
myStatistics.AbonentList.Add(a3.Phone, a3.Name);
myStatistics.AbonentList.Add(a4.Phone, a4.Name);
myStatistics.AbonentList.Add(a5.Phone, a5.Name);
Console.WriteLine(myStatistics.AbonentList[685472]);
}
}
Main
Abonent,
Hashtable AbonentList (myStatistics.AbonentList) Values. Phone.
, Add() Hashtable :
. 134.
HashTable
, .
,
() (. 134).
ArrayList
ArrayList, Hashtable,
System.Collections,
158
.
.
ArrayList 16
object.
ArrayList 32 .
.
.
.
using System;
using System.Collections;
namespace ClassArrayList
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
ArrayList ar = new ArrayList();
ar.Add("A");
ar.Add("AB");
ar.Add("ABC");
ar.Add("ABCD");
ar.Add("ABCDE");
ar.Add("ABCDEF");
ar.Add("ABCDEFG");
ar.Add("ABCDEFGH");
ar.Add("");
ar.Add("");
Console.WriteLine(" :\n");
foreach (object element in ar)
{
Console.WriteLine(element);
}
ar.Remove("ABCD");
Console.WriteLine(" :\n");
foreach (object element in ar)
{
Console.WriteLine(element);
}
ar.Insert(6, "XYZ");
Console.WriteLine(" \n :\n");
foreach (object element in ar)
{
159
. 135. ArrayList
Console.WriteLine(element);
}
ar.Clear();
Console.WriteLine(" :\n");
foreach (object element in ar)
{
Console.WriteLine(element);
}
} // end Main()
} // end class
} // end namespace
135.
135 ,
ArrayList ,
object.
.
4.5. 4
1. , . 4.1.2.
2. - . 4.1.3.
3. , , , .
4. . ? (. 12)?
5. UML- , btnFill_Click (. 4.1.3).
6.
InfoMessage (. 9).
7. , (. 13), .
8. , (7-) .
9. , 2 (. 2.6).
160
10. , (9-) .
11. , (. 14), SQL Management Studio
. ,
.
12. , (. 15), Visual Studio 2008 . , .
13. , 75 76.
14. Command (.4.3.2)
13. :
Microsoft Access Microsoft SQL Server.
15. , . 4.3.2, CommandType CommandText
Command.
16. ExecuteNonQuery,
ExecuteScalar, ExecuteReader Command?
17.
?
18. Windows-,
. 4.3.3 (. 87 90),
ExecuteScalar Command / .
19. ?
20.
. , EasyTransaction (. 101, 102).
21. ( ) Questions Variants (. DataTable
DataColumn 4.4.1)?
22.
DataTable?
23. . 4.4.1, ,
dsTests ( DataSet),
questID ( DataTable) (Questions) (Variants),
ForeignKeyConstraint.
161
24. , 23,
.
GetChanges DataSet
.
25. , 24, .
: ) ,
) ,
)
ItemArray DataRow, ) DataRow BeginEdit EndEdit.
26. RowState, RowVersion DataRow?
27. DataTable ?
28. , RowVersion
(. RowVersion . 4.4.2), ColumnChanged
ColumnChanging, (
RowChanged, RowChanging,
RowDeleted, RowDeleting).
29. , 24,
DataGridView, DataGridView.
30. ?
?
31. ?
?
32. , (.
. 4.4.4, . 132-133), .
33. Hashtable, ArrayList? ?
, .
. ,
, . , . , . , .
162
ADO .NET, Microsoft, .NET Framework. ADO .NET, Microsoft
.NET Framework, , ( 136).
ADO .NET
. 136. ADO.NET
,
IsolationLevel, : Chaos, ReadUncommited, ReadCommited, RepeatableRead, Snapshot,
Serializable.
ADO .NET .
ADO .NET ,
. System.Transactions
.
ADO.NET .
.NET , .NET Framework
OleDb, SqlClient, OracleClient, ODBC
. IDbTransaction System.Data.
. ,
.
, . , ADO .NET,
. DataAdapter.
, . , , .
, . ,
, ,
, .
,
.
.
, .
ADO .NET DataSet DataTable.
ADO.NET , .
ADO .NET:
DataSet. DataSet
ADO.NET. ,
, .
165
DataTable. .
DataColumn, DataRow, .
DataView. .
DataRelation. ,
.
ADO.NET
, , , .
166
ACID, 164
ADO .NET, 5, 163
, 163
DCL, 93
deny, 93
grant, 93
revoke, 93
DDL, 38, 92
alter, 92
as, 70
create, 92
create procedure, 70
create table, 38
drop, 80, 92
DML, 39
delete, 39, 89
insert, 39, 89
update, 39, 89
ER-, 10
SQL, 32
BEGIN TRAN, 117
between, 36
COMMIT TRAN, 117
DECLARE, 117
from, 33
group by, 36
in.., 36
inner join, 73
left join, 73
like, 37
null, 37
order by, 35
percent, 35
ROLLBACK TRAN, 117
select, 33
where, 33, 36
SQL-,
avg, 37, 94
count, 36, 93
max, 37, 94
min, 37, 94
sum, 37
Windows-, 42, 56, 60, 61, 88,
98, 108, 112, 113, 129, 133, 137, 138, 145,
150, 154
, 7, 11
(), 7
, (), 7
, , 8
, 13
, 13
, 13
, 7
, 32
, 97
Bottom, 104
Cascade, 127
Detached, 137
Details, 104
Fill, 88
input, 113
InputOutput, 113
None, 128
output, 113
ReturnValue, 113
SetDefault, 128
SetNull, 128
StoredProcedure, 86
TableDirect, 86
Text, 86
, 132
, 44
Database, 44
Object, 44
Service, 44
(Binding Source), 49
ArrayList, 158
Hashtable, 157
OleDbCommand, 87
OleDbConnection, 87
OleDbDataAdapter, 87
OleDbException, 65
Parameters, 113
SqlCommand, 88
SqlConnection, 88
SqlDataAdapter, 88
SqlError, 64
SqlException, 64
TableAdapter, 53
, 17
, 12
, 38
, 38
167
, 7,
12, 127
, 12
Binding Source, 42
BindingNavigator, 50
CheckBox, 152
DataGridView, 47, 56, 129
DataSet, 47
ListBox, 104, 113
ListView, 104
Panel, 50
Splitter, 104, 113
TableAdapter, 48
TextBox, 50
, 135
AcceptChanges, 138
Add, 99, 125, 158
BeginEdit, 135
ClearErrors, 132
Close, 61
CreateCommand, 87
Delete, 136
Dispose, 61
EndEdit, 135
ExecuteNonQuery, 89, 91
ExecuteReader, 95, 104
ExecuteScalar, 93, 104
Fill, 54
Get<>, 105
GetChanges, 130
HasVersion, 139
InitializeComponent, 56, 86
Read, 96
RejectChanges, 132, 138
Remove, 136
Update, 53
, 65
, 10
, 15
, 12
(1) , 13
(2) , 13
(3) , 13
(4) , 13
Command, 86
, , 87
CommandText, 56, 85
ConnectionString, 56, 59
, 7
, 129
AcceptRejectRule, 127
DeleteRule, 127
UpdateRule, 127
, , 89, 93, 95, 119,
157, 159
, 56
System.Collections, 158
System.Data, 56
System.Data.OleDb, 56
System.Data.SqlClient, 56
, , 67, 113
, 71
, 83, 108
, 75
, 78
, 80, 83
, 78
, 66
, 67
,
DataBindings, 51
168
Advanced, 51
AllowDBNull, 127
AutoIncrement, 125
AutoSize, 61
BindingSource, 50
Columns, 104, 125
CommandType, 86
Connection, 86
Constraint, 127
DataSource, 43
DataType, 53
Direction, 113
Dock, 56, 88, 104
Errors, 65
Expression, 130
ForeignKeyConstraint, 127
GridLines, 104
HasErrors, 132
ItemArray, 135
Message, 65
NativeError, 65
PrimaryKey, 126
Relations, 53
RowFilter, 150, 152
Rows, 135
RowState, 137
RowStateFilter, 150
RowVersion, 138, 139
SelectCommand, 145
Sort, 151
SQL State, 65
TableMappings, 145
Tables, 53
Unique, 125, 127
UniqueConstraint, 127
View, 104
, 19
--, 20
--, 20
--, 20
, 9
CheckedChanged, 152
ColumnChanged, 143
ColumnChanging, 143
Disposed, 61
InfoMessage, 61
RowChanged, 143
RowChanging, 143
RowDeleted, 143
RowDeleting, 143
StateChange, 61
, 59
, 12
, 15
, 20
, 16, 24
, 19
, 115
, 120
, 121
Dirty reads, 121
Non-repeatable reads, 121
Phantom reads, 121
, 121
Chaos, 123
Read committed, 121
Read uncommitted, 121
Repeatable read, 122
Serializable, 122
Unspecified, 123
, 122, 123
, 8
, 10
, , 36
169
1. ADO .NET
[
].
:
http://ru.wikipedia.org/wiki/ADO.NET/, . . .
2. ADO. NET [ ] / . . , . . : http://www.codenet.ru/db/other/ado-dot-net/, . . .
3. ADO.NET: [ ]. :
http://www.cyberguru.ru/dotnet/ado-net/adonet-overview.html,
.
. .
4. C# 2005 / . , . , . , . ,
. , . . ; -; : ,
2007.
5. , . . .
- / . . . . : , 2003.
6. , . . Windows- Visual C# /
. . . . : . , -
., 2007.
7. , . . Microsoft ADO. NET / . . . . : . , - ., 2007.
8. , . # 2005 : / .
. . , . . . : , 2008.
9. , . . Windows / . . .
, , 2003.
10., . . C# 2.0 / . . .
. : . , -
., 2007.
11. # 2005 : / . . . ,
. . . : , 2008.
12., . Microsoft Windows C# / . . 2 . : . . . : - , 2002.
170
C#. DO .NET
. .
020640 22.10.97.
29.10.2009. 6084/16.
. . . 10,23. 100 . 1200.
, 432027, . , . , 32.
, 432027, . , . , 32.
171