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

http://www.intuit.

ru/department/se/msadonet/

Microsoft ADO .NET


: ..


ADO.NET
Microsoft SQL Server 2000 Microsoft Access, .NET
Framework. 90 Visual C#,
,
.
, :
Microsoft Access Microsoft SQL 2000, ,
SQL, SQL Server Enterprise Manager SQL Query Analyzer.
, .
,
ADO.NET. XML , DTD, XSL, XSD.
: Connection,
, Command ExecuteNonQuery, ExecuteScalar
ExecuteReader, , DataSet, DataTable DataColumn,
, , ,
DataSet, XML,
Command,
CommandBuilder, , DataAdapter DataSet,
XML- .

Microsoft ADO.NET.

C#
Windows- Visual C#
C# 2.0

ASP.NET 2.0
Microsoft ASP.NET

1.
. Microsoft Access.
Microsoft Access Microsoft SQL.
SQL Server Enterprise Manager.
Microsoft SQL Microsoft Access. SQL Server Enterprise
Manager. Microsoft SQL . SQL.
. like. .
DML
1

2. ADO .NET
- ADO .NET. Data Form Wizard.
ADO .NET. ( DataTable DataColumn).
DataRelation. ( DataRow). DataAdapter. DBConnection
DBCommand. ADO .NET. Server Explorer.
ADO .NET. CommandText. ConnectionString.
. Connection Command
3. Microsoft Access
. .
CurrencyManager. Microsoft Access, .
. Microsoft Access,
. . Microsoft Access
, .
4. Microsoft SQL Server
Microsoft SQL Server .
InfoMessage StateChange Connection. .
. Microsoft SQL Profiler
5.
. . .
SQL Query Analyzer, SQL Server Enterprise Manager, Visual Studio
.NET
6. Command
Command. CommandType CommandText. ExecuteNonQuery,
ExecuteScalar ExecuteReader Command. DataReader.
Command Windows-. .
, DataReader, ListBox, ListView,
DataGrid
7. .
. NextResult
DataReader. . Dirty reads, Non-repeatable reads
Phantom reads. Read uncommitted, Read committed, Repeatable read,
Serializable, Chaos, Unspecified. Microsoft Access
8. DataTable, DataRow DataColumn
DataSet, DataTable DataColumn. DataTable
DataColumn. Unique Constraint ForeignConstraint. ,
. DataRow. RowState RowVersion.
DataTable
9. DataView.
DataView. . .
DataGrid. DataGrid.
PrimaryKey. . HashTable ArrayList
10. XML
SGML, HTML XML. XML-. XML-.
(well-formed) XML-.
2

(CSS). CSS XML. (valid) XML. (DTD). XSL XSLT. XML. XSL-

11. DataSet. XML-


XML- (XSD). XSD- Visual Studio .NET.
DataSet. DataSet.
XML- XSD- DataSet.
ReadXml ReadXmlSchema.
DataSet. WriteXml WriteXmlSchema
12. DataAdapter.
Command
DataAdapter. Fill. Table Mappings. QuickWatch.
MissingMappingAction. MissingSchemaAction.
TableMappings DataSet . .
SqlCommand .
OleDbCommand
13. .
CommandBuilder
MS SQL Server.
MS Access.
Command Builder. . GetChanges Merge
DataSet. , . Optimistic
concurrency.
14. Web-
web-. Windows-, web-.
web-. web-. ,
IIS.

1. :
. Microsoft Access.
Microsoft Access Microsoft SQL.
SQL Server Enterprise Manager.
Microsoft SQL Microsoft Access. SQL Server Enterprise
Manager. Microsoft SQL . SQL.
. like. .
DML
http://www.intuit.ru/department/se/msadonet/1/

2. : ADO .NET
- ADO .NET. Data Form Wizard.
ADO .NET. ( DataTable DataColumn).
DataRelation. ( DataRow). DataAdapter. DBConnection
DBCommand. ADO .NET. Server Explorer.
3

ADO .NET. CommandText. ConnectionString.


. Connection Command

ADO .NET
o - ADO .NET. Data Form
Wizard
o ADO .NET
o ( DataTable DataColumn)
o DataRelation
o ( DataRow)
o DataAdapter
o DBConnection DBCommand
o ADO .NET
o Server Explorer
o ADO .NET
o CommandText
o ConnectionString
o . Connection
o Command

ADO .NET

- ADO .NET. Data Form


Wizard
Data Form Wizard Visual Studio .NET ,
, . , ,
.
Microsoft Access BDTur_firm.mdb,
. : - ""
" " Windows-.
Visual Studio .NET, , - Windows Application.
DataWizardMDB.
Solution Explorer DataWizardMDB
Add/Add New Item.
Data Form Wizard, . 2.1:

. 2.1. Data Form Wizard


DataFormMDB.cs.
"Next". DataSet,
, dsTourists.
"Choose a data connection" .
, "New Connection".
" "
. " "
OLE DB (. 2.2):

. 2.2.
Microsoft Jet 4.0 OLE DB Provider
Microsoft Aceess (mdb). "" (
"") (. 2.3 ):

. 2.3.
1 (...) BDTur_firm.mdb,
. 2
- ,
"Admin" .
, " "
" ". ""
""
. , "OK".
, .
,
. Available Items
Selected Items, .
- Selected Items,
. , ,
. : "" "
" (. 2.4):

. 2.4. ,
.
,
. , .

( ). TouristsInfoTourists.
(Parent table) - "" (Child table) " ". " " .
, Relations,
Next.

. 2.5.
(), . (.
2.5).
-
( All records in a grid )
( Single records in individual control ). .
-
. . ,
"Finish".
- "
". "Include password", (
),
(. 2.6).

. 2.6.
9

. , , , Form1. Form1
:
[STAThread]

static void Main()


{
Application.Run(new Form1());

DataFormMDB Windows Form Designer generated code


:
static void Main()
{

Application.Run(new DataFormMDB ());

Solution Explorer Form1.cs . ,


, DataFormMDB (. 2.7):

. 2.7.
.
Load. .
.
Add Delete, Cancel. Cancel All.
Update -
BDTur_firm.mdb.

ADO .NET. ,
, .
10

DataForm Wizard ,
.
DataWizardMDB
(Code\Glava1 DataWizardMDB).

ADO .NET
ADO .NET . DataSet
ADO .NET, ( , )
,
. , Data Form Wizard,
, ,
Update , .. RBProduct.mdb,
. ? ,
DataSet, . Update
DataSet . DataSet c
-
.
, .
, ,
, .
,
, .
, c .
DataSet. , , , - .
, DataSet ADO .NET.
DataSet DataTable DataRelation.
DataSet, .., .
Tables DataTableCollection,
DataTable .

( DataTable DataColumn)
DataTable DataSet. DataTable
. , DataTable
DataColumn.
DataColumn - DataTable. DataColumn
DataType, ,
DataColumn. , ,
. , DataTable,
,
.

DataRelation
DataSet Relations,
DataRelationCollection, DataRelation.
11

DataRelation (
- (). ,
DataColumn ).

( DataRow)
Rows DataTable () .
.
.

DataAdapter
DataSet - , .
DataSet
DataAdapter. - , , -
. DataAdapter Fill()
DataSet.

DBConnection DBCommand
DBConnection .
. DBCommand
( , SQL
). DBConnection DBCommand
DataSet, .

ADO .NET
, Visual Studio .NET
, . ,
,
-
ADO .NET , .
ADO .NET
.
Microsoft Acess xtreme1), Microsoft
Visual Studio.NET, - Microsoft SQL2) NorthwindCS .
Customer(s)3). - Customer
Windows-.
Microsoft Access, xtreme Microsoft SQL, NorthwindCS
Visual Studio .NET, , - Windows Application.
VisualDataMDB VisualDataSQL
DataGrid, Dock
"Fill". ToolBox Data (.
2.8).
12

. 2.8. Data ADO.NET


OleDbDataAdapter SqlDataAdapter
. OleDbDataAdapter
- , . 2.2 - 2.3.
OleDbDataAdapter .
SqlDataAdapter " "
(. 2.9).

13

. 2.9. Microsoft OLE DB Provider for SQL Server


"" ( "") (. 2.10).

14

. 2.10.
SQL, , 1
( local ) - ".". 2 :
SQL Server - . 3
NorthwindCS.
- . ,
, (. 2.11 . 2.12):

15

. 2.11. OleDbDataAdapter

16

. 2.12. SqlDbDataAdapter
Microsoft Access SQL- -
. Microsoft SQL Server
SQL-, ( stored procedure ),
.
. SqlDataAdapter ,
: SQL-.
- SQL- (Generate SQL statements) -
. "
": "Query Builder_" (. 2.13).
- , OleDbDataAdapter:

. 2.13.
Customer ( Customers ), Add Close.
Query Builder (All Columns), . 2.14:

17

. 2.14. . (All Columns),



OK. "Generate the SQL statements", ,
SQL- , :
SELECT
SELECT
Customer.*
Customers.*
FROM
FROM
Customer
Customers

,
"" SQL- , .
Next. " " (View Wizard Results)
. ,
. 2.15 2.16:

18

. 2.15. OleDbDataAdapter

19

. 2.16. SqlDbDataAdapter
? Access
- SQL- SELECT,
- INSERT, UPDATE, DELETE. SQL Server
.
(. . 2.10) .
Finish. OleDbDataAdapter (. . 2.6),
.
: oleDbDataAdapter1
oleDbConnection1 VisualDataMDB sqlDbDataAdapter1 sqlDbConnection1
VisualDataSQL. oleDbDataAdapter1 ( sqlDbDataAdapter1 )
OleDbData Adapter ( SqlDataAdapter ),
. oleDbConnection1 ( sqlDbConnection1 )
. , (
DataAdapter1 ) ( Connection1 ) .
DataSet - "",
, . oleDbDataAdapter1 (
sqlDbDataAdapter1 ), . .
"Generate DataSet"
DataSet4) (. 2.17).

. 2.17. DataSet
"Generate DataSet" - dsCustomer dsCustomers
.
20

, "" .
. ,
, dataGrid1. DataSource
( ) dsCustomer1 (.
2.18).

. 2.18. dataGrid1

(+). , , - DataSet ( dsCustomer1 ). :
using System.Data.OleDb;
//

OleDb

private void Form1_Load(object sender, System.EventArgs e)


{
oleDbDataAdapter1.Fill(dsCustomer1);
}
using System.Data.SqlClient;
// SQL
private void Form1_Load(object sender, System.EventArgs e)
{
sqlDataAdapter1.Fill(dsCustomers1);
}

Fill oleDbDataAdapter1
( sqlDbDataAdapter1 ) dsCustomer1. ,
, "" DataSet,
- , DataSet
dataGrid1.
. (+), "Customer".
(. 2.19 2.20):

21

. 2.19. VisualDataMDB

. 2.20. VisualDataSQL
5) Code\Glava1\VisualDataMDB VisualDataSQL.

Server Explorer
Visual Studio .NET
- Server Explorer.
, . .
Server_Explorer. View Server Explorer (
Ctrl+Alt+S). Server Explorer.
Data Connections "Add Connection" (. 2.21):

22

. 2.21.
" ", (.
. 2.2 2.3). xtreme -
, Server Explorer (.
2.22):


. 2.22. Server Explorer
(+) , Tables,
Customer (. 2.23).

23

. 2.23. xtreme
(. . 2.6) "Include
Password".
: oleDb Connection1
oleDbDataAdapter1. oleDbDataAdapter1, ,
"Generate DataSet". "DataSet
dsCustomer" "". DataGrid,
Dock - Fill, DataSource - dsCustomer
. :
private void Form1_Load(object sender, System.EventArgs e)
{
oleDbDataAdapter1.Fill(dsCustomer1);
}

. ,
.
xtreme
Server Explorer.
.
Solution Explorer
- . (. 2.24):

24


. 2.24. Customers NorthwindCS

ADO .NET

.
. ,
.
.
Microsoft Access, xtreme
Customer

Microsoft SQL, NorthwindCS


Customers.

Visual Studio .NET, , - Windows Application.


ProgrammDataMDB ProgrammDataSQL
DataGrid, Dock
"Fill". .
:
using System.Data.OleDb; using System.Data.SqlClient;

InitializeComponent DataAdapter:
public Form1()
{
//

25

// Required for Windows Form Designer support


//
InitializeComponent();
OleDbDataAdapter dataAdapter =
new OleDbDataAdapter(CommandText, ConnectionString);
}
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
SqlDataAdapter dataAdapter =
new SqlDataAdapter(CommandText, ConnectionString);
}

DataAdapter CommandText ConnectionString.


string CommandText SQL-
Customer, onnectionString -
, , ,
. .
? , , ,
, . VisualDataMDB VisualDataSQL. . Windows
Form Designer generated code, (+). :
CommandText:
this.oleDbSelectCommand1.CommandText = @"SELECT Address1, Address2, City,
[Contact First Name], [Contact Last Name], [Contact Position],
[Contact Title], Country, [Customer Credit ID], [Customer ID],
[Customer Name], [E-mail], Fax, [Last Year's Sales], Phone,
[Postal Code], Region, [Web Site] FROM Customer";
this.sqlSelectCommand1.CommandText = "SELECT CustomerID,
CompanyName, ContactName, ContactTitle, Address, City, Region,
PostalCode, Country, Phone, Fax FROM Customers";

ConnectionString1):
this.oleDbConnection1.ConnectionString = @"
Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;
Jet OLEDB:Database Locking Mode=1;
Jet OLEDB:Database Password=;Data Source=""E:\Program
Files\Microsoft Visual Studio .NET
2003\Crystal Reports\Samples\Database\xtreme.mdb"
";Password=;Jet OLEDB:Engine Type=5;Jet OLEDB:Global Bulk
Transactions=1;Provider=""Microsoft.Jet.OLEDB.4.0"";Jet
OLEDB:System database=;Jet OLEDB:SFP=False;Extended Properties=;
Mode=Share Deny None;Jet OLEDB:New Database Password=;Jet
OLEDB:Create System Database=False;Jet OLEDB:Don'Jet
Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica
Repair=False;User ID=Admin;Jet OLEDB:Encrypt Database=False";
this.sqlConnection1.ConnectionString = "workstation
id=7EA2B2F6068D473;packet size=4096;integrated security=SSPI;
data source=\"(local) \";persist security info=False;
initial catalog=NorthwindCS";

26

, ,
ProgrammDataMDB ProgrammDataSQL Form 1
string :
string CommandText = @"SELECT Address1, Address2,
City, [Contact First Name], [Contact Last Name], [Contact Position],
[Contact Title], Country, [Customer Credit ID], [Customer ID],
[Customer Name], [E-mail], Fax, [Last Year's Sales], Phone, [Postal Code],
Region, [Web Site] FROM Customer";
string ConnectionString = @"Jet OLEDB:Global Partial
Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;
Jet OLEDB:Database Password=;Data Source=""E:\Program
Files\Microsoft Visual Studio .NET 2003\Crystal
Reports\Samples\Database\xtreme.mdb"";Password=;
Jet OLEDB:Engine Type=5;Jet OLEDB:Global Bulk
Transactions=1;Provider=""Microsoft.Jet.OLEDB.4.0"";
Jet OLEDB:System database=;Jet OLEDB:SFP=False;Extended Properties=;
Mode=Share Deny None;Jet OLEDB:New Database Password=;
Jet OLEDB:Create System Database=False;Jet OLEDB:Don'
Jet Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica
Repair=False;
User ID=Admin;Jet OLEDB:Encrypt Database=False";
string CommandText = "SELECT CustomerID, CompanyName, ContactName,
ContactTitle, Address, City, Region, PostalCode, Country, Phone,
Fax FROM Customers";
string ConnectionString = "workstation id=7EA2B2F6068D473;packet
size=4096;integrated security=SSPI;data sou" +
"rce=\"(local)\";persist security info=False;initial
catalog=NorthwindCS";

CommandText ConnectionString.
DataAdapter, ,
cmdText conString, cmt cns - , ,
, Form1. Visual Studio
.NET - CommandText
ConnectionString, , ,
, .
- ProgrammDataMDB ProgrammDataSQL.
.
, DataSet:
DataSet ds = new DataSet();

Customer ds :
dataAdapter.Fill(ds, "Customer");

C dataGrid1 (
) Customer ds:
dataGrid1.DataSource = ds.Tables["Customer"].DefaultView;

! . , ,
xtreme Customer, NorthwindCS Customers ( "s" ). .
27

? , "Customer", Fill
dataAdapter -
. ( DataSource )
dataGrid1 Customer,
Fill. , DataSet,

ADO .NET. , :
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "Bezimyannaya");
dataGrid1.DataSource = ds.Tables["Bezimyannaya"].DefaultView;

- . ,
DataSet? -
.
, ,
. DataSet ,
.
2) - xtreme:
using
using
using
using
using
using
using

System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.Data.OleDb;

namespace ProgrammDataMDB
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
string CommandText = @"SELECT Address1, Address2, City,
[Contact First Name], [Contact Last Name], [Contact
Position],
[Contact Title], Country, [Customer Credit ID], [Customer
ID],
[Customer Name], [E-mail], Fax, [Last Year's Sales],
Phone, [Postal Code], Region, [Web Site] FROM Customer";
string ConnectionString = @"Jet OLEDB:Global Partial Bulk
Ops=2;Jet
OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet
OLEDB:Database Password=;Data Source=""E:\Program
Files\Microsoft Visual Studio .NET 2003\Crystal
Reports\Samples\Database\xtreme.mdb"";Password=;Jet
OLEDB:Engine Type=5;Jet OLEDB:Global Bulk
Transactions=1;Provider=""Microsoft.Jet.OLEDB.4.0"";
Jet OLEDB:System database=;Jet OLEDB:SFP=False;Extended
Properties=;Mode=Share Deny None;Jet OLEDB:New Database
Password=;
Jet OLEDB:Create System Database=False;Jet OLEDB:Don'

28

Jet Copy Locale on Compact=False;Jet OLEDB:Compact Without


Replica Repair=False;User ID=Admin;
Jet OLEDB:Encrypt Database=False";
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
OleDbDataAdapter dataAdapter =
new OleDbDataAdapter(CommandText, ConnectionString);
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "Bezimyannaya");
dataGrid1.DataSource =
ds.Tables["Bezimyannaya"].DefaultView;
//
// TODO: Add any constructor code after
InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
Windows Form Designer generated code
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
}
}

- NorthwindCS:
using System;
using System.Drawing;

29

using
using
using
using
using

System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.Data.SqlClient;

namespace ProgrammDataSQL
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
string CommandText = "SELECT CustomerID, CompanyName,
ContactName, ContactTitle, Address, City, Region," +
" PostalCode, Country, Phone, Fax FROM Customers";
string ConnectionString = "workstation
id=7EA2B2F6068D473;packet
size=4096;integrated security=SSPI;data sou" +
"rce=\"(local)\";persist security info=False;initial
catalog=NorthwindCS";

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
SqlDataAdapter dataAdapter =
new SqlDataAdapter(CommandText, ConnectionString);
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "Customer");
dataGrid1.DataSource =
ds.Tables["Customer"].DefaultView;
//
// TODO: Add any constructor code after
InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
Windows Form Designer generated code

30

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
}

CommandText
SQL-.
CommandText SQL-,
. ,
CommandText. ProgrammDataSQL
CommandText. . string ommandText
, DataGrid CustomerID, ContactName, Country Phone.
, SQL-:
string CommandText = "SELECT CustomerID, ContactName, Country,
Phone FROM Customers";

.
(. 2.25):

. 2.25.
, "":
string CommandText = "SELECT CustomerID, ContactName, Country,
Phone FROM Customers where ContactName like 'M%'";

. "M" (. 2.26).

31

. 2.26.
SQL
CommandText .
insert, update delete -
.
ommandText (Code\Glava1\
ommandText).

ConnectionString
ConnectionString ,
.
, ( -
) . ,
xtreme Northwind.
xtreme, ProgrammDataMDB:
string ConnectionString = @"Jet OLEDB:Global Partial Bulk Ops=2;
Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;
Jet OLEDB:Database Password=;Data Source="
"E:\Program Files\Microsoft Visual Studio .NET 2003\Crystal
Reports\Samples\Database\xtreme.mdb"";Password=;
Jet OLEDB:Engine Type=5;Jet OLEDB:Global Bulk
Transactions=1;Provider=""Microsoft.Jet.OLEDB.4.0"";
Jet OLEDB:System database=;Jet OLEDB:SFP=False;Extended Properties=;
Mode=Share Deny None;Jet OLEDB:New Database Password=;
Jet OLEDB:Create System Database=False;Jet OLEDB:Don'
Jet Copy Locale on Compact=False;
Jet OLEDB:Compact Without Replica Repair=False;User ID=Admin;
Jet OLEDB:Encrypt Database=False";

NorthwindCS, ProgrammDataSQL:
string ConnectionString =

32

"workstation id=7EA2B2F6068D473;packet size=4096;


integrated security=SSPI;data sou" +
"rce=\"(local)\";persist security info=False;
initial catalog=NorthwindCS";

.
2.1 .
2.1. ConnectionString

Provider ()

,
OleDbConnection
Connection Timeout Connect
Timeout (

)
. 15
Initial Catalog (

)
Data Source ( ) SQL-,
, Microsoft Access
Password ()
SQL Server
User ID ( ID) SQL Server
Workstation ID

Integrated Security Trusted
, ,
Connection (
. True, False SSPI - .

(SSPI - True)
)
Persist Security Info ( False,

, ,
, -
. True
.
False
ConnectionString
. , ,

.
:

Provider ( OLE DB)


Data Source
Initial Catalog
User ID/Password
Persist Security Info

ProgrammDataMDB Programm DataSQL.


ConnStringMDB ConnStringSQL. ConnectionString
:
xtreme, ConnStringMDB:
33

string ConnectionString = @"Provider=""Microsoft.Jet.OLEDB.4.0"";


Data Source=""E:\Program Files\Microsoft
Visual Studio .NET 2003\Crystal Reports\Samples\Database\xtreme.mdb"";
User ID=Admin;Jet OLEDB:Encrypt Database=False";

NorthwindCS, ConnStringSQL:
string ConnectionString = "workstation
id=7EA2B2F6068D473;integrated security=SSPI;
data source=\"(local)\";persist security info=False;
initial catalog=NorthwindCS";

,
.
, DataAdapter
, ?
DataAdapter, . , ,
ADO .NET - DataWizardMDB. ,
Windows Form Designer generated code :
this.oleDbConnection1.ConnectionString = @"Jet OLEDB:Global Partial Bulk
Ops=2;
Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;
Jet OLEDB:Database Password=;Data Source="
"D:\Uchebnik\Code\Glava4\RBProduct.mdb"
";Password=;Jet OLEDB:Engine Type=5;
Jet OLEDB:Global Bulk Transactions=1;Provider="
"Microsoft.Jet.OLEDB.4.0"";
Jet OLEDB:System database=;Jet OLEDB:SFP=False;Extended Properties=;
Mode=Share Deny None;Jet OLEDB:New Database Password=;
Jet OLEDB:Create System Database=False;Jet OLEDB:Don'
Jet Copy Locale on Compact=False;
Jet OLEDB:Compact Without Replica Repair=False;
User ID=Admin;Jet OLEDB:Encrypt Database=False";

DataAdapter Toolbox (
Data) , DBConnection,
ConnectionString (. 2.27):


. 2.27. sqlConnection1 VisualDataSQL

34

. Connection
.
, Microsoft Access
255 . ,
,
.
,
.
DataAdapter (, Fill ), ,
. , DataAdapter ,
.
- .
:

;
;
.

Connection.
ConnectionMDB. DataGrid
Toolbox Dock Fill.
. :
using System.Data.OleDb;

Form1 InitializeComponent Connection:


OleDbConnection conn = new OleDbConnection(ConnectionString);

conn ConnectionString.
onn:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnectionString;

ConnectionString.
ConnStringMDB (
xtreme).
string ConnectionString = @"Provider=""Microsoft.Jet.OLEDB.4.0""; Data Source=""E:\Program
Files\Microsoft Visual Studio .NET 2003\Crystal Reports\Samples\Database\xtreme.mdb"";User
ID=Admin;Jet OLEDB:Encrypt Database=False";
, Open Connection:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnectionString;
conn.Open();

35

Command
Command SQL- .
, Connection Command -
Connection:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnectionString;
conn.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = conn;

Connection CreateCommand,
- Command,
Connection:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnectionString;
conn.Open();
OleDbCommand myCommand = conn.CreateCommand();

.
SQL-, .
, , , CommandText.
CommandText, Customer:
string ommandText = @"SELECT Address1, Address2, City,
[Contact First Name], [Contact Last Name], [Contact Position],
[Contact Title], Country, [Customer Credit ID], [Customer ID],
[Customer Name], [E-mail], Fax, [Last Year's Sales], Phone,
[Postal Code], Region, [Web Site] FROM Customer";

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, "Customers");

36

DataSource dataGrid1:
dataGrid1.DataSource = ds.Tables["Customers"].DefaultView;

:
conn.Close();

! . ,
, .
ConnectionMDB:
using
using
using
using
using
using
using

System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;
System.Data.OleDb;

namespace ConnectionMDB
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
string ConnectionString =
@"Provider=""Microsoft.Jet.OLEDB.4.0"";
Data Source=""E:\Program Files\Microsoft Visual Studio
.NET 2003\Crystal Reports\Samples\Database\xtreme.mdb"
";User ID=Admin;Jet OLEDB:Encrypt Database=False";
string commandText = @"SELECT Address1, Address2, City,
[Contact First Name], [Contact Last Name], [Contact
Position],
ID],

[Contact Title], Country, [Customer Credit ID], [Customer


[Customer Name], [E-mail], Fax, [Last Year's Sales],
Phone, [Postal Code], Region, [Web Site] FROM Customer";
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
OleDbConnection conn = new
OleDbConnection(ConnectionString);
//OleDbConnection conn = new OleDbConnection();
//conn.ConnectionString = ConnectionString;
conn.Open();
OleDbCommand myCommand = new OleDbCommand();

37

myCommand.Connection = conn;
myCommand.CommandText = commandText;
//OleDbCommand myCommand = conn.CreateCommand();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
dataAdapter.SelectCommand = myCommand;
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "Customers");
dataGrid1.DataSource = ds.Table
["Customers"].DefaultView;
conn.Close();
//
// TODO: Add any constructor code after
InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
Windows Form Designer generated code
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
}

ConnectionString connectingText myCommand


DataAdapter ( ProgrammDataMDB
ProgrammDataSQL ).
Connection SQL
, .
Connection Command:
using System.Data.SqlClient;
string CommandText = "SELECT CustomerID, CompanyName, ContactName,
ContactTitle, Address, City, Region, PostalCode, Country, Phone,

38

Fax FROM Customers";


string connectionString = "workstation id=7EA2B2F6068D473;
integrated security=SSPI;data source=\"(local)\";
persist security info=False;initial catalog=NorthwindCS";
SqlConnection conn = new SqlConnection(connectionString);
//SqlConnection conn = new SqlConnection();
//conn.ConnectionString = ConnectionString;
conn.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = conn;
myCommand.CommandText = CommandText;
//SqlCommand myCommand = conn.CreateCommand();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = myCommand;
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "Customers");
dataGrid1.DataSource =
ds.Tables["Customers"].DefaultView;
conn.Close();

ConnectionMDB
ConnectionSQL (Code\Glava1\ ConnectionMDB ConnectionSQL).
,
Microsoft Visual Studio .NET ADO .NET
, .
.
-
. ,
ADO .NET , .

3. : Microsoft Access
. .
CurrencyManager. Microsoft Access, .
. Microsoft Access,
. . Microsoft Access
, .

Microsoft Access
o
o . CurrencyManager
o Microsoft Access, .

o Microsoft Access,
.
o Microsoft Access ,
.

39

! 3, 4 ,

http://www.intuit.ru/department/se/msadonet/3/

4. : Microsoft SQL Server


Microsoft SQL Server .
InfoMessage StateChange Connection. .
. Microsoft SQL Profiler

Microsoft SQL Server


o Microsoft SQL Server
o Connection
o
o . Microsoft SQL Profiler

Microsoft SQL Server

Microsoft SQL Server

Microsoft SQL Server


. :
Windows (Windows Authentication) (Mixed Mode
Authentication). , ,
, (. 4.1):

40

. 4.1. Windows

Windows. SQL Server
. " "
(. 4.2):

41

. 4.2. Windows " "



, Microsoft SQL Server.
SQL Server Enterprise Manager,
"".
"SQL Server Properties" "Security",
"SQL Server and Windows" (. 4.3).

42


. 4.3.
. "Security"
, "Logins". "BULTIN\" "sa".
. - "sa" (system administrator) -
,
. ,
"". "Password" "SQL Server Login Properties"
"12345" (. 4.4):

43


. 4.4. "sa"
, Northwind,
"sa". Windows-,
"VisualSQLUser_sa". DataGrid,
Dock "Fill". Toolbox Data
SqlDataAdapter. .
" " (local),
(sa) (12345), Northwind (. 4.5):

44

. 4.5. " ". VisualSQLUser_sa


" ".
(12345) connectionString.
-
. "Data Adapter
Configuration Wizard", Customers.
(. 4.6).

. 4.6.
DataAdapter,
Properties "Generate dataset". DataSet,
. DataSet,
DataGrid:
public Form1()
{

45

InitializeComponent();
sqlDataAdapter1.Fill(dataSet11);
dataGrid1.DataSource = dataSet11.Tables[0].DefaultView;

. Customers (. 4.7):

. 4.7. VisualSQLUser_sa
VisualSQL User_sa
(Code\Glava2\ VisualSQLUser_sa).
.
Windows-, "ProgrammSQLUser_sa".
DataGrid, Dock "Fill".
:
using System.Data.SqlClient;

connectionString commandText:
string connectionString = "workstation id=9E0D682EA8AE448;
user id=sa;data source=\"(local)\";" +
"persist security info=True;initial catalog=Northwind;password=12345";
string commandText = "SELECT * FROM Customers";

ADO .NET:
public Form1()
{

InitializeComponent();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connectionString;
SqlDataAdapter dataAdapter = new
SqlDataAdapter(commandText, conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGrid1.DataSource = ds.Tables[0].DefaultView;
conn.Close();
}

Programm SQLUser_sa
(Code\Glava2\ProgrammSQLUser_sa).
Microsoft Access
. "" " "
46

Microsoft SQL Server.


.

Connection
Connection ,
.
4.1.
4.1. Connection

Disposed
Dispose
InfoMessage

StateChange .

Dispose Connection
. Close.
StateChange Disposed.
Windows- "ConnectionEventsSQL". Size
"600;300". DataGrid,
Dock "Fill". Panel, Dock
"Bottom". ,
:
label1,
Location
8; 8
Size
208; 80
Text
labe2,
Location
232; 8
Size
208; 80
Text
button1,
Name
btnFill
Location
488; 40
Text

:
using System.Data.SqlClient;

connectionString commandText:
string connectionString = "workstation id=9E0D682EA8AE448;
packet size=4096;integrated security=SSPI;data source=\"(local)\";
persist security info=False;initial catalog=Northwind";

47

string commandText = "SELECT * FROM Customers";

ADO .NET Click "btnFill":


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();
}

IntelliSense - , TAB (. 4.8):

. 4.8. -
48

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 .
, - .
, (. 4.9):

. 4.9. ConnectionEventsSQL
( Dispose )
, - . ,
.
, .
, ,
.
Connection EventsSQL
(Code\Glava2\ ConnectionEventsSQL).
, Microsoft Access.
,

49

Connection EventsSQL "ConnectionEventsMDB".


. :
using System.Data.OleDb;

connectionString commandText:
string connectionString = @"Provider=""Microsoft.Jet.OLEDB.4.0"
"; Data Source=""E:\Program Files\Microsoft Visual Studio .NET 2003\Crystal
Reports\Samples\Database\xtreme.mdb"";User ID=Admin;Jet OLEDB:Encrypt
Database=False";
string commandText = "SELECT * FROM Customer";

xtreme.mdb. Click
"btnFill" :
private void btnFill_Click(object sender, System.EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
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);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(commandText,
conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGrid1.DataSource = ds.Tables[0].DefaultView;
// Dispose, Close,
// .
conn.Dispose();
}

conn_Disposed conn_StateChange .
- (. 4.10):

50

. 4.10. ConnectionEventsMDB
Connection EventsMDB
(Code\Glava2\ ConnectionEventsMDB).


.
.

.

Microsoft SQL Server SqlException SqlErro r.
,
( 4.2):
4.2. SQL Server

17

4060

18456

SQL Server,
( 4.3):
4.3. SQL Server

11-16
17-19

20-25



,
.

.

Windows- "ExceptionsSQL". Size


"600;380".
DataGrid, Dock "Fill". Panel,
:
panel1,
Dock
Location
Size

Right
392; 0
200; 346
51

, :
textBox1,

Name
txtDataSource
Location
8; 8
Size
184; 20
Text

textBox2,

Name
txtInitialCatalog
Location
8; 40
Size
184; 20
Text

textBox3,

Name
txtUserID
Location
8; 72
Size
184; 20
Text

textBox4,

Name
txtPassword
Location
8; 104
Size
184; 20
Text
1)
label1,

Location
16; 136
Size
176; 160
Text
button1,

Name
btnConnect
Location
56; 312
Size
96; 23
Text

.
:
using System.Data.SqlClient;

ADO .NET
"":
private void btnConnect_Click(object sender, System.EventArgs e)
{
SqlConnection conn = new SqlConnection();
label1.Text = "";
try
{
//conn.ConnectionString = "workstation id=9E0D682EA8AE448;data
source=\"(local)

52

//\";" + "persist security info=True;initial catalog=Northwind;


//user id=sa;password=12345";
// ConnectionString
// , :
conn.ConnectionString =
"initial catalog=" + txtInitialCatalog.Text + ";" +
"user id=" + txtUserID.Text + ";" +
"password=" + txtPassword.Text + ";" +
"data source=" + txtDataSource.Text + ";" +
"workstation id=9E0D682EA8AE448;persist security info=True;";
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM
Customers", conn);
DataSet ds = new DataSet();
conn.Open();
dataAdapter.Fill(ds);
dataGrid1.DataSource = ds.Tables[0].DefaultView;
}
catch (SqlException OshibkiSQL)
{
foreach (SqlError oshibka in OshibkiSQL.Errors)
{
// Number oshibka
// SQL Server
switch (oshibka.Number)
{
case 17:
label1.Text += "\n !";
break;
case 4060:
label1.Text += "\n !";
break;
case 18456:
label1.Text += "\n
!";
break;
}
// Class oshibka
// SQL Server,
// Message -
label1.Text +="\n"+oshibka.Message + "
SQL Server: " + oshibka.Class;
}
}
// :
catch (Exception ex)
{
label1.Text += "\n : " + ex.Message;
}
finally
{
conn.Dispose();
}
}

.
,
, . .
,
DataGrid (. 4.11):

53


. 4.11. ExceptionsSQL
Exceptions SQL (Code\Glava2\
ExceptionsSQL).
ExceptionsSQL "ExceptionsMDB".
:
textBox1,
Name
Location
Size
Text
textBox2,
Name
Location
Size
Text
textBox3,

txtDataBasePassword
8; 16
184; 20

txtUserID
8; 48
184; 20

54

Name
Location
Size
Text

TxtPassword
8; 80
184; 20

:
using System.Data.OleDb;

"" :
private void btnConnect_Click(object sender, System.EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
label1.Text = "";
try
{
// conn.ConnectionString = @"Provider=""Microsoft.Jet.OLEDB.4.0"";
//Data Source=""D:\Uchebnik\Code\Glava2\BDwithUsersP.mdb"";
Jet OLEDB:System database=""D:\Uchebnik\Code\Glava2\BDWorkFile.mdw"";
User ID=Adonetuser;Password=12345;Jet OLEDB:Database Password=98765;";
// ConnectionString
// , :
conn.ConnectionString =
"Jet OLEDB:Database Password=" + txtDataBasePassword.Text
+ ";" + "User ID=" + txtUserID.Text + ";" +
"password=" + txtPassword.Text + ";" +
@"Provider=""Microsoft.Jet.OLEDB.4.0"";Data
Source=""D:\Uchebnik\Code\Glava2\BDwithUsersP.mdb"";
Jet OLEDB:System database=""D:\Uchebnik\Code\Glava
\BDWorkFile.mdw"";";
OleDbDataAdapter dataAdapter =
new OleDbDataAdapter("SELECT * FROM ", conn);
DataSet ds = new DataSet();
conn.Open();
dataAdapter.Fill(ds);
dataGrid1.DataSource = ds.Tables[0].DefaultView;
}
catch (OleDbException oshibka)
{
//
for (int i=0; i < oshibka.Errors.Count; i++)
{
label1.Text+= " " + i
+ "\n" + ": " +
oshibka.Errors[i].Message + "\n" +
" NativeError: " +
oshibka.Errors[i].NativeError + "\n" +
": " + oshibka.Errors[i].Source +
"\n" + " SQLState: " +
oshibka.Errors[i].SQLState + "\n";
}
}
// :
catch (Exception ex)
{
label1.Text += "\n : " +

55

}
finally
{
}

ex.Message;

conn.Dispose();

(. 4.12). Message
, Microsoft Office 2003.
NativeError ( ) ,
. SQL State
,
( ExceptionsSQL) .

. 4.12. ExceptionsMDB
, ,
.

,
. , - ,
.
56

Exceptions MDB
(Code\Glava2\ ExceptionsMDB).

. Microsoft SQL Profiler


- ,
,
. ,

Close, :
. ,
,
?
(. 4.13, ).
,
, , 60 .

(. 4.13, ). , , 35 ,
,
,
(. 4.13, ).

57


. 4.13. . - ,
, - ,
-

,
. :
,
.
, , ,
, .. ,
.
. .
. ,
( ),
(
), .
58

.NET
. Close ,
. 60 ,
, . -
, ,
onnectionString .
OLE DB:
OLE DB Services=-4;

SQL Server:
Pooling=False;

Close .
Microsoft SQL Server
( 4.4).
4.4. MS SQL Server

Connection ( .),
0
Lifetime
.

. , ,
, , .
0 ,
- (60
.)
Enlist
True
1)
Max Pool
.
100
Size


Min Pool

0
Size

Pooling

True
, ,
ConnectionString.

Profiler2), Microsoft SQL Server 2000.
"" Microsoft SQL Server .
"File \ New \ Trace" ( Ctrl+N).
.
Query Analyzer. "sa" (.
4.14):

59

. 4.14.
Trace Properties ( ),
, ( "Save to file")
(. 4.15).

. 4.15.
60

"Run" . ,
. ExceptionsSQL,
"" - SQL Profiler
(. 4.16).


. 4.16.
,
- "Audit Logout". ,
ExceptionsSQL (. 4.17).


. 4.17. "ExceptionsSQL"

61

ExceptionsSQL Visual Studio .NET, . ConnectionString


( "Pooling"):
conn.ConnectionString =
"initial catalog=" + txtInitialCatalog.Text + ";" +
"user id=" + txtUserID.Text + ";" +
"password=" + txtPassword.Text + ";" +
"data source=" + txtDataSource.Text + ";" +
"workstation id=9E0D682EA8AE448;persist security info=True;Pooling=False";

"Audit Logout" (. 4.18):


. 4.18.
, , -
. .

5. :
. . .
SQL Query Analyzer, SQL Server Enterprise Manager, Visual Studio
.NET
http://www.intuit.ru/department/se/msadonet/5/

62

63

Оценить