Académique Documents
Professionnel Documents
Culture Documents
NET
User Interface
XML
...
Base Classes
Common Language Runtime
...
Benefits of ADO.NET
Interoperability through use of XML
Open standard for data that describes itself
Human readable text
Used internally but accessible externally
Can use XML to read and write and move data
Maintainability
Separation of data logic and user interface
ADO.NET-related Namespaces
ADO.NET
System.Data
.SqlTypes
.SqlClient
.Common
.OleDb
ADO.NET Namespaces
System.data
System.Data.Common
System.Data.OleDb
System.Data.SqlClient
System.Data.SqlTypes
System.Data
.SqlClient
SqlCommand
SqlConnection
SqlDataReader
SqlDataAdapter
.OleDb
OleDbCommand
OleDbConnection
OleDbDataReader
OleDbDataAdapter
SqlConnection
SqlConnection
Connects to databases.
Two provider-specific classes
SqlConnection
OleDbConnection.
SqlConnection
Represent a unique session with a data source
Create, open, close a connection to a data
source
Functionality and methods to perform
transactions
When an instance of SqlConnection is created, the
read/write properties are set to initial values.
String conStr=server=191.1.32.170; database=bali;
uid=sa;pwd=;
SqlConnection aConn = new SqlConnection(conStr);
aConn.Open();
// Execute Queries using SqlCommand Class
aConn.Close();
SqlConnection Constructor
public SqlConnection();
Initializes a new instance of the SqlConnection
class.
public SqlConnection(string);
Initializes a new instance of the SqlConnection
class when given a string containing the
connection string.
SqlConnection Example
using System;
using System.Data.SqlClient;
public class DataBaseConnection {
public static void Main () {
string strCon = server=vas\\vas01; database=pubs;
UID=sa;PWD=shivhari;
SqlConnection objCon1 = new SqlConnection();
objCon1.ConnectionString = strCon
SqlConnection objCon2 = new
SqlConnection(strCon)
objCon1.Open();
objCon2.Open();
System.Console.WriteLine(objCon1.State);
System.Console.WriteLine(objCon2.State);
}
}
SqlConnection-Properties
Property
Description
ConnectionString
ConnectionTimeout
Database
DataSource
PacketSize
ServerVersion
State
WorkstationId
SQLConnection.ConnectionString
Unlike OLE DB or ADO, the connection string that is
returned is the same as the user-set ConnectionString
minus security information, if Persist Security Info
value is set to false (default).
The SQL Server .NET Data Provider does not persist
or return the password in a connection string unless
you set Persist Security Info to true.
SQLConnection.ConnectionString
The ConnectionString property can be set only when
the connection is closed.
When the connection string is set, all of these
properties are updated, except when an error is
detected. In this case, none of the properties are
updated.
SqlConnection properties return only those settings
contained in the ConnectionString.
Resetting the ConnectionString on a closed
connection resets all connection string values (and
related properties) including the password.
SQLConnection Properties
Connect Timeout / Connection Timeout (15)
The length of time (in seconds) to wait for a
connection to the server before terminating the
attempt and generating an error.
Connection Lifetime(0)
When a connection is returned to the pool, its
creation time is compared with the current time,
and the connection is destroyed if that time span
(in seconds) exceeds the value specified by
connection
lifetime.
Useful
in
clustered
configurations to force load balancing between a
running server and a server just brought on-line.
SQLConnection.Properties
Data Source/Server (null)
The name or network address of the instance of
SQL Server to which to connect.
Initial Catalog / Database (null)
The name of the database.
SQLConnection.Properties
.
Packet Size (8192)
Size in bytes of the network packets used to
communicate with an instance of SQL Server.
Password /Pwd ()
The password for the SQL Server account logging
on.
Pooling ('true)
When true, the SQLConnection object is drawn
from the appropriate pool, or if necessary, is
created and added to the appropriate pool.
Connection Addition
Connection Removal
Connection Pooling
When the maximum pool size is reached, the
request is queued.
The object pooler satisfies these requests by
reallocating connections as they are released back
into the pool.
If the time-out period (determined by the Connect
Timeout connection string property) elapses before
a connection object can be obtained, an error
occurs.
You must always close the Connection when you are
finished using it.
Connection Pooling
Connection Removal
The object pooler will remove a connection from the
pool if the connection lifetime has expired, or if the
pooler detects that the connection with the server
has been severed.
This can be detected only after attempting to
communicate with the server. If a connection is
found that is no longer connected to the server, it is
marked as invalid.
The object pooler periodically scans connection
pools looking for objects that have been released to
the pool and are marked as invalid.
These connections are then permanently removed.
Connection Pooling
Connection Removal
It is possible for an apparently valid connection to
be drawn from the pool although the associated
server has disappeared.
When this occurs, an exception is generated.
However, the user must still close the connection to
release it back into the pool.
Connection Pooling
Controlling Connection Pooling with Connection String
Keywords
Max Pool Size(100) - Min Pool Size(0)
Pooling('true)
When true, the SQLConnection object is drawn
from the appropriate pool, or if necessary,
created and added to the appropriate pool.
SQLConnection Methods
Open
Close
ChangeDatabase
CreateCommand
BeginTransaction
database
for
an
open
object
SqlConnection.Open() Method
Opens a database connection with the property settings
specified by the ConnectionString.
public void Open();
Exceptions
An SqlException would be thrown if a connection-level
error occurs while opening a connection.
An InvalidOperationException would be thrown if the
data source or server is not specified or if the
connection is already open.
The SqlConnection draws an open connection from the
connection pool if one is available.
Otherwise, it establishes a new connection to an instance of
SQL Server.
SqlConnection.Close()
Closes the connection to the database. This is the preferred
method of closing any open connection.
public void Close();
Exceptions
An SqlException would be thrown if a connection-level
error occurs while closing a connection.
The Close method rolls back any pending transactions. It then
releases the connection to the connection pool, or closes the
connection if connection pooling is disabled.
An application can call Close more than one time. No
exception is generated.
SqlConnection.ChangeDatabase() Method
Changes the current database for an open SqlConnection.
public void ChangeDatabase( string database );
Exceptions
ArgumentException Invalid DataBase name
InvalidOperationException -The connection is not open.
SqlException - Cannot change databases.
SqlConnection.CreateCommand()
SqlConnection.BeginTransaction()
Begins a database
SqlTransaction object.
transaction
and
returns
an
SqlConnection.BeginTransaction()
SqlConnection objCon1 = new SqlConnection(strCon);
ObjCon1.Open();
SqlCommand objCmd1= new SqlCommand();
SqlTransaction objTran1;
objCmd1.Transaction = objTran1;
Cont.
SqlConnection.BeginTransaction()
try {
objCmd1.CommandText = "Insert into Region (RegionID, RegionDescription)
VALUES (100, 'Description')";
objCmd1.ExecuteNonQuery();
objCmd1.CommandText = "Insert into Region (RegionID, RegionDescription)
VALUES (101, 'Description')";
objCmd1.ExecuteNonQuery();
objTran1.Commit();
Console.WriteLine("Both records are written to database.");
}
Cont.
SqlConnection.BeginTransaction()
catch(Exception ex)
{
objTran1.Rollback("Tran1");
Console.WriteLine(ex.ToString());
Console.WriteLine("Neither record was written to database.");
}
finally
{
// close the connection after Committing or Rolling back
objCon1.Close();
}
}
SqlTransaction Class
Represents a Transact-SQL transaction to be made in
a SQL Server database. This class cannot be inherited
Implementation
public sealed class SqlTransaction :
MarshalByRefObject, IDbTransaction, IDisposable
The application creates a SqlTransaction object by
calling BeginTransaction on the SqlConnection
object.
All subsequent operations associated with the
transaction (for example, committing or aborting the
transaction), are performed on the SqlTransaction
object.
SqlTransaction.IsolationLevel Property
The isolation level is measure of the extent to which changes made
outside a transaction are visible inside that transaction.
for
this
transaction.
The
default
Therefore,
is
the
IsolationLevel Enumeration
The IsolationLevel remains in effect until explicitly changed, but
it can be changed at any time.
The new value is used at execution time, not parse time. If
changed during a transaction, the expected behavior of the
server is to apply the new locking level to all statements
remaining.
IsolationLevel Enum
Chaos
ReadCommitted
ReadUncommitt
ed
Dirty Reads
Processing Sequence:
A writes a value out
B reads the value in
A does a rollback (restoring the original value)
Consequence:
B has performed a dirty read
B has an incorrect value
Processing Sequence:
B reads a value in
A writes the value out
A does a commit (making its change permanent)
Consequence
B has performed a non-repeatable read
B has the wrong value
If B rereads, it will get a different value
Processing Sequence:
A reads a set of rows in
B writes a row that would
been in As set, had B been
quicker.
have
Consequence
A doesnt have the data it thought
it had
If A performs the same query,
phantoms (new records) will appear
Asetofrowsinatable
Phantom Reads
A
SqlTransaction.Rollback() Method
Rolls back a transaction from a pending state.
public void Rollback();
public void Rollback(string);
SqlTransaction.Save() Method
Creates a savepoint in the transaction that can be used to roll
back a portion of the transaction, and specifies the savepoint
name.
public void Save( string savePointName);
Exception
InvalidOperationException is thrown
If this transaction is already committed
(or)
The connection is broken
SqlTransaction.Save() Method
Savepoints offer a mechanism to roll back portions of
transactions.
You create a savepoint using the Save method, and then
later call the Rollback method to roll back to the savepoint
instead of rolling back to the start of the transaction.
SqlCommand
SqlCommand
Information submitted to a database as a query via a
Connection object
Two provider-specific classes
SqlCommand
OleDbCommand
SQLCommand Class
Represents a T-SQL command or a Stored
Procedure call
Different methods to execute record-returning
queries and non-query statements.
ExecuteNonQuery() No Data Returned
ExecuteReader(,) - Result set captured into DataReader
ExecuteScalar() First column of first row
ExecuteXmlReader() Builds XmlReader
SQLCommand constructors
public SqlCommand();
public SqlCommand(string);
SQLCommand Example
public void CreateSqlCommandDemo() {
SqlConnection objCon1 = new SqlConnection("user
id=sa;password=;initial catalog=northwind;data
source=demoSQLServer");
objCon1.Open();
SqlTransaction objTran1 = objCon1.BeginTransaction();
string strSelectQuery = "SELECT * FROM Categories ORDER
BY CategoryID";
SqlCommand objCmd1 = new SqlCommand(strSelectQuery,
objCon1,objTran1);
objCmd1.CommandTimeout = 20;
}
SQLCommand Properties
Connection
CommandType
Transaction
Parameters
SQLCommand Example
public void CreateMySqlCommandDemo() {
SqlCommand objCmd1 = new SqlCommand();
objCmd1.CommandText = "SELECT * FROM Categories
ORDER BY CategoryID";
objCmd1.CommandTimeout = 15;
objCmd1.CommandType = CommandType.Text;
}
CommanType Enum
Text
StoredProcedure
TableDirect
SqlCommand Methods
ExecuteNonQuery
ExecuteReader
ExecuteScalar
ExecuteXmlReader
Cancel
CreateParameter
to
Prepare
ResetCommandTimeout
the
SqlCommand.ExecuteNonQuery()
Executes a Transact-SQL statement against the Connection
and returns the number of rows affected.
public int ExecuteNonQuery();
Usage Scenarios :
SqlCommand.ExecuteReader()
Sends the CommandText to the Connection and builds a
SqlDataReader.
public SqlDataReader ExecuteReader();
public SqlDataReader
ExecuteReader(CommandBehavior);
CommandBehavior Enumeration
CommandBehaviour Enum
CloseConnection
SchemaOnly
SequentialAccess
SqlCommand.ExecuteReader()
Method strSelectQuery,string
public void CreateSqlDataReaderDemo(string
strCon) {
SqlConnection objCon1 = new SqlConnection(strCon);
SqlCommand objCmd1 = new SqlCommand(strSelectQuery, objCon1);
objCmd1.Connection.Open();
SqlDataReader objDataReader =
objCmd1.ExecuteReader(CommandBehavior.CloseConnection);
while(objDataReader.Read())
{
Console.WriteLine(objDataReader.GetString(0));
}
objDataReader.Close();
//objCon1.Close();}
SqlCommand.ExecuteScalar()
Executes the query, Method
and returns the first column of
the
first row in the resultset returned by the query. Extra
columns or rows are ignored.
public object ExecuteScalar();
Usage Scenarios
To retrieve a single value (aggregate) from a database.
Less code in this case that DataReader
Formatting :
objCmd1.CommandText
=
"select
NumberOfRegions from region";
Int count = (int) objCmd1.ExecuteScalar();
count(*)
as
SqlCommand.ExecuteXmlReader()
Sends the CommandText to the Connection and builds an
XmlReader object.
public XmlReader ExecuteXmlReader();
Usage Scenarios:
Transact-SQL a valid FOR XML clause
Formatting:
SqlCommand mySqlCommand = new
SqlCommand("select * from customers FOR XML
AUTO, mySqlConnection);
SqlCommand.Methods
SqlCommand.Cancel()
Cancels the execution of a SqlCommand .
public void Cancel();
SqlCommand.CreateParameter()
public SqlParameter CreateParameter();
SqlCommand.Prepare()
SqlParameter
SqlParameter Class
Represents a parameter to a SqlCommand,
optionally, its mapping to DataSet columns.
This class cannot be inherited.
Parameter names are not case sensitive.
and
SqlParameter.ParameterName
Property
is
specified
in
the
form
SqlParameter.Direction Property
Gets or sets a value indicating whether the parameter
is input-only, output-only, bidirectional, or a stored
procedure return value parameter.
public ParameterDirection Direction {get; set;}
ParameterDirection Enum
Input
InputOutput
Output
ReturnValue
SqlParameter.Size Property
Gets or sets the maximum size, in bytes, of the data
within the column.
The default value is inferred from the the parameter
value.
The Size property is used for binary and string types.
For nonstring data types and ANSI string data, Size
refers to the number of bytes.
For Unicode string data, Size refers to the number of
characters.
The count for strings
terminating character.
does
not
include
the
Precision
SqlParameters Collection
SqlParametersCollection Class
Collects all parameters relevant to a SqlCommand as well as their
respective mappings to Dataset Columns.
Count
Item
SqlParametersCollection Methods
Method
Add
Insert
Remove
RemoveAt
Clear
Contains
IndexOf
Description
Overloaded. Adds a SqlParameter to the
SqlParameterCollection.
Inserts a SqlParameter in the collection
at the specified index.
Removes the specified SqlParameter
from the collection.
Overloaded. Removes the specified
SqlParameter from the collection.
Removes all items from the collection.
Overloaded.
Indicates
whether
a
SqlParameter exists in the collection.
Overloaded. Gets the location of a
SqlParameter in the collection.
SqlParametersCollection.Add()
Method
SqlParametersCollection.Insert()
Method
SqlParametersCollection.Remove()
Method
Removes the
collection.
specified
SqlParameter
from
the
SqlParametersCollection.RemoveAt()
Removes the
collection.
specified
SqlParameter
from
the
SqlParametersCollection.CopyTo()
Copies
SqlParameter
objects
from
SqlParameterCollection to the specified array.
public void CopyTo( Array array, int index );
SqlParameter[] myParamArray = new
SqlParameter[myCmd.Parameters.Count - 1];
myCmd.Parameters.CopyTo(myParamArray, 0);
the
SqlParametersCollection.Clear()
Method
// ...
SqlParametersCollection.Contains()
Indicates whether a SqlParameter exists in the
collection.
OverLoads
public bool Contains(object);
public bool Contains(string);
SqlParametersCollection.IndexOf()
Gets the location of a SqlParameter in the collection.
OverLoads:
public int IndexOf(object);
public int IndexOf(string);
public void SearchForSqlParams() {
// ...
// ...
if (!objCmd.Parameters.Contains("Description"))
System.Console.WriteLine("ERROR: no such parameter in the
collection");
else
System.Console.WriteLine("match on parameter #" +
objCmd.Parameters.IndexOf("Description").ToString()); }
SqlDataReader
SqlDataReader
Forward-only data access
Lightweight programming model
Less overhead than using SqlDataAdapter
SqlDataReaderClass
Provides a means of reading a forward-only tablulardata-stream(TDS) of rows from a SQL Server database.
SqlDataReaderClass Properties
Property
Description
Field Count
Is Closed
Item
Records
Affected
You must explicitly call the Close method when you are
through using the SqlDataReader to use the associated
SqlConnection for any other purpose.
SqlDataReader.IsDbNull() Method
SqlDataReader.Read() Method
SqlDataAdapter
SqlDataAdapter Class
Bridge between the DataSet and the
data store
Inherited from the DataAdapter class
data store
DataAdapter
DataSet
SqlDataAdapter class
Represents a set of data commands and a database
connection which are used to fill the DataSet and update a
SQL Server database.
The SqlDataAdapter, serves as a bridge between a DataSet
and SQL Server for retrieving and saving data.
The SqlDataAdapter provides this bridge by mapping Fill,
which changes the data in the DataSet to match the data in
the data source
Update, which changes the data in the data source to match
the data in the DataSet, using the appropriate Transact-SQL
statements against the data source .
The SqlDataAdapter also includes the SelectCommand,
InsertCommand, DeleteCommand, UpdateCommand, and
TableMappings properties for facilitating the loading and
updating of data
SqlDataAdapter Constructor
public SqlDataAdapter();
public SqlDataAdapter(SqlCommand);
public SqlDataAdapter(qrystring, SqlConnection);
SqlDataAdapter Properties
Property
Description
SelectCommand
InsertCommand
DeleteCommand
SqlDataAdapter Methods
Fill (inherited from
DbDataAdapter)
SqlDataAdapter.Update() Method
public int Update(DataRow[]);
public override int Update(DataSet);
public int Update(DataTable);
System.Data Namespace
Contains the basis and bulk of ADO.NET
Data-centric namespace
Provides the means to work on and with
your data!
Tables
DataTable
DataView
DataRow(s)
Relations
DataRelation
DataColumn
Constraint(s)
DataRelation
DataTable
DataTable
DataViewManager
The DataTable
May be mapped to a physical table in the data
source
Can be related to one another through
DataRelations
Optimistic concurrency or locking - model
Properties of Interest:
Columns: Returns ColumnsCollection of
DataColumns
Rows: Returns DataRow objects as a RowsCollection
ParentRelations: Returns the RelationsCollection
Constraints: Returns the tables ConstraintsCollection
DataSet: Returns the DataSet of the DataTable
PrimaryKey: Gets the DataColumns that make up the
tables primary key
Creating a DataView
// Code for myTable Customers with Name column not shown
DataView view1 = new DataView( myTable );
DataView view2 = new DataView( myTable );
// Creates Ascending view of Customers by Name
view1.Sort = Name ASC;
// Bind to UI element(s)...
DataGrid myGrid = new DataGrid();
myGrid.SetDataBinding( view1, Customer);
//...
Summary