ADO.NET is a set of classes that allows .NET Framework programmers to interact with data sources The data source is a database such as Microsoft SQL Server, Microsoft Access, Oracle,.
Trang 3 ADO.NET is a set of classes that allows NET Framework programmers to interact with data sources
The data source is a database (such as Microsoft SQL Server, Microsoft Access, Oracle, ), but it could also be a text file,
an Excel spreadsheet, or an XML file
The System.Data namespace contains the core data access classes in the NET Framework
The design goals of ADO.NET:
Leverage current ActiveX Data Objects (ADO) knowledge
Support the n-tier programming model
Integrate XML support
Introduction to ADO.NET
Trang 4 The two main components of ADO.NET for accessing and manipulating data:
The NET Framework Data Providers
There isn't a single set of classes that allow you to interact with different types of data sources and different types of databases
A way to communicate with the right data source using the
Trang 5ADO.NET Components (cont.)
ADO.NET architecture
Trang 6Data Provider Description Namespace
Trang 7 Core objects of NET Framework Data Providers
ADO.NET Components
The NET Framework Data Providers (cont.)
Object Description
Connection Establishes a connection to a specific data source The
connection helps identify the database server, the database name, user name, password, and other parameters
Command Executes a command against a data source: get data,
modify data, run stored procedures, and send or retrieve parameter information
DataReader Reads a forward-only, read-only stream of data from a data
source
DataAdapter Populates a DataSet and resolves updates with the data
source: the bridge between the DataSet object and the data source
Trang 8 Each data provider provides an implementation of the
Connection, Command, DataAdapter, and
DataReader objects
ADO.NET Components
The NET Framework Data Providers (cont.)
Slide 9
Trang 9 Connected data access through the DataReader objects of
data provider This object provides forward-only, read-only access to data in the data source
Disconnected data access is achieved through the
DataAdapter object This object loads data in the DataSet that works independent of database and can edit the data
Connected and disconnected data access
DataReader
DataSet DataAdapter
Connected
Trang 10 What is a Connection object?
Creating and configuring Connection objects
Working with Connection pools
Handling Connection errors
Enumerating the available SQL Servers
Securing sensitive Connection string data
Connection objects
Slide 11
Trang 11What is a Connection object?
A Connection object is a representation of an connection
to a specific data source
The Connection helps identify the database server, the database name, user name, password, and other
parameters
Trang 12How to create Connection?
Creating Connections in Server Explorer
Trang 13Read only Get the name of the current database after a connection is opened or the database name specified in the connection string before the connection is opened
DataSource Read only Get the name of the database server to which it is connected.
State Read only Get a string that describes the state of the connection.
Trang 14Connection methods
Name Description
Open Open a database connection with the settings
specified by the ConnectionString You cannot open
the connection that is opened
Close Close the connection to the database This is the
preferred method of closing any open connection.
15
Trang 15Open connection
Open the connection with database Northwind:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = " Data Source=localhost; Initial
Catalog=Northwind; Integrated Security=SSPI";
conn.Open();
Open the connection with database QLSV.accdb:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;
Data Source = QLSV.accdb";
conn.Open();
Trang 16Connection String
Parameter Name Description
Data Source Identifies the server Could be local machine, machine domain name, or IP
Address.
Initial Catalog Database name.
Integrated
Security Set to SSPI to make connection with user's Windows login
User ID Name of user configured in SQL Server Password Password matching SQL Server User ID.
Slide 17
Trang 17What is connection pooling? (p 225)
Connection pooling enables the reuse of existing
connections
This technique allows storage of connection has been
established in Connetion Pool in a time period, and
applications needed to access the database may require a connection from this Connection Pool
That improves performance, increase the scalability of an application
Connections have the same configuration
Each time call Open method with a unique connection
string, a new pool is created
Trang 18Controlling Connection pooling options
By default, connection pooling is enabled when creating
ADO.NET connection (Pooling = True)
Control connection pooling behavior by setting connection string
Pooling
Min Pool Size
Max Pool Size
19
Trang 19Configuring Connections to Use
Connection Pooling
Configuring Connection Pooling with SQL Server
Connections
Data Source=SqlServerName;Initial Catalog=DatabaseName;
Integrated Security=True;Min Pool Size=5
Configuring Connection Pooling with OLE DB Connections
Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=DatabaseName.mdb;OLE DB Services=-1
(See page 228-229)
Trang 20Handling Connection Errors
.NET Exceptions
21
Trang 21Handling Connection Errors
OleDbException class exposes properties that contain
details of the exception condition These include:
A Message property that contains text describing the error.
A Number property that contains the error number, which
uniquely identifies the type of error.
A State property that contains additional information about
the invocation state of the error.
An Errors collection, which contains detailed error
information about the errors.
Trang 22Handling Connection Errors
try {
conn.Open();
// using conn }
catch ( OleDbException ex)
Trang 23Enumerating the Available SQL (p.237)
Using Instance property of the SqlDataSourceEnumerator class to call the GetDataSources method
The GetDataSources method returns a Data-Table that contains information for each SQL server that is visible on the network
System.Data.Sql.SqlDataSourceEnumerator instance =
System.Data.Sql.SqlDataSourceEnumerator.Instance;
dataGridView1.DataSource = instance.GetDataSources();
Trang 24Enumerating the Available SQL
Why no SQL Servers appear?
Network traffic
Firewall
Service SQL Browser need to run
25
Trang 26Securing Sensitive Connection String Data (p 241)
Protect your application
Secure information such as user IDs, data source names, passwords,…
The suggested method of implementing security in
applications
Windows Authentication (Integrated Security)
27
Trang 27Securing Sensitive Connection String Data (p 241)
The suggested method of implementing security in
applications (cont.)
Using the application configuration file (app.config)
Add\Add new item, select 'Application Configuration file'
Trang 28Securing Sensitive Connection String Data (p 241)
The suggested method of implementing security in
applications (cont.)
Encrypt config file: available in the NET Framework (Lab: p 243)
29
Trang 29 Creating and configuring Command objects
Executing Command objects
Working with parameters in SQL commands
Command objects
Trang 30 Command object is a object which is used to
Execute SQL statements ( INSERT, DELETE, UPDATE or SELECT
statement)
Execute Stored procedures
Create Command object:
XxxCommand cmd = new XxxCommand ();
XxxCommand cmd = new XxxCommand (string
commandText);
XxxCommand cmd = new XxxCommand (string
commandText, XxxConnection connection);
Slide 31
Creating Command objects
Trang 32Example database
Slide 33
Trang 33 Example 1: Querying data
OleDbCommand cmd = new OleDbCommand ();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text ;
cmd.CommandText = "select * from SinhVien ";
Example 2: Querying data
OleDbCommand cmd = new OleDbCommand ();
cmd.Connection = conn;
cmd.CommandType = CommandType.TableDirect ;
cmd.CommandText = "SinhVien ";
Example 1, 2
Trang 34 Example 3: Inserting data
OleDbCommand cmd = new OleDbCommand ();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
"VALUES ('CSE', 'Khoa Khoa Học và Kỹ Thuật Máy Tính') " ;
Example 4: Deleting data
OleDbCommand cmd = new OleDbCommand ();
Trang 35 Example 5: Updating data
OleDbCommand cmd = new OleDbCommand ();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
SET GVCN = 'Tran Thi B'
WHERE MaLop = 'CDTH10K'";
Example 6: Getting single values
OleDbCommand cmd = new OleDbCommand ();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
Example 5, 6
Trang 36 Example 7: Querying data using stored procedure
OleDbCommand cmd = new OleDbCommand();
Trang 37 To execute a Command object, using methods:
ExecuteScalar(): returns an object
Executes SQL statements or Stored procedures that return a single value (SELECT statement)
ExecuteNonQuery(): returns an integer
Executes SQL statements or Stored procedures and returns the number of rows that were affected but do not return data
(INSERT, DELETE, UPDATE, CREATE TABLE statement)
ExecuteReader(): returns a DataReader object
Executes SQL statements or Stored procedures that returns the DataReader object (SELECT statement)
Executing Command objects
Trang 38 How to create a query with undefined value?
Concatenate string in query
Trang 39 What is Parameterized query?
Types of Parameter
How to pass value to Parameter query?
Working with Parameters in SQL
commands
Trang 40 Parameterized queries are queries that have one or more embedded parameters in the SQL statement
SQL Server uses the @ symbol as a prefix to denote named parameters
Other databases (such as Microsoft Office Access and OLE DB data sources) represent parameters with a question mark (?) symbol
What is Parameterized query?
Trang 41 Types of Parameter:
Input parameter (default)
send data to the database
Output parameter
retrieve information coming out of the database
InputOutput parameter
The type of parameter is designated in the Direction
property of the parameter
With a parameter, you can set its Direction property to Input ,
Output , InputOutput , or ReturnValue
Types of Parameter (p.274)
Trang 421. Declare an instance of the Parameter class with its name
and data type
2. Set Value for parameter
3. Choose ParameterDirection (if needed)
4. Add parameter to the Parameters collection of the