Session 7
Session 7
PROGRAMMING II
Slide 2
ADO.NET Architecture
• The two main components of ADO.NET for accessing and
manipulating data are
– the .NET Framework data providers
– the DataSet
• A .NET Framework data provider is used for connecting to a
database, executing commands, and retrieving result
• Those results are either:
– processed directly
– placed in a DataSet in order to be exposed to the user as needed
– combined with data from multiple sources
– remoted between tiers.
Slide 3
Data Providers
• In addition to the core classes .NET Framework data provider also contains these classes:
• Transaction, CommandBuilder, ConnectionStrngBuilder,
• Parameter, Exception, Error and ClientPErmission
Slide 5
ADO.NET DataSets
• The DataSet is a memory-resident representation of
data that provides a consistent relational
programming model regardless of the data source.
• The methods and objects in a DataSet are consistent
with those in the relational database model.
• DataSet contains a collection of zero or more tables
represented by DataTable objects.
Slide 6
DataSet Object Model
Slide 7
DataSet Object Model cont’d
• The DataTableCollection contains all the DataTable objects in a
DataSet.
• A DataTable is defined in the System.Data namespace and
represents a single table of memory-resident data.
• A collection of rows (DataRow) represented by the
DataRowCollection
• A collection of columns (DataColumn) in a DataTable is
represented by a DataColumnCollection
• A collection of constraints on a DataTable is represented by a
ConstraintCollection
• A DataView enables you to create different views of the data
stored in a DataTable
Slide 8
Retrieving and Modifying Data in ADO.NET
Slide 9
Connecting to a Data Source
• Each .NET Framework data provider included with
the .NET Framework has a DbConnection object
– Data Provider for OLE DB includes an OleDbConnection
object
– Data Provider for SQL Server includes a SqlConnection
object
– Data Provider for ODBC includes an OdbcConnection
object
– Data Provider for Oracle includes an OracleConnection
object
Slide 10
Connecting to SQL Server
• The using block in C# automatically disposes of the connection
when the code exits the block, even in the case of an unhandled
exception
• A connection string contains initialization information that is
passed as a parameter from a data provider to a data source. E.g.
“Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword; “
{
connection.Open();
// Do work here.
}
Slide 11
Connecting to an OLE DB Data Source
// Assumes connectionString is a valid connection string.
using (
OleDbConnection connection = new OleDbConnection(connectionString)
)
{
connection.Open();
// Do work here.
}
Slide 12
Connecting to an ODBC Data Source
// Assumes connectionString is a valid connection string.
using (
OdbcConnection connection = new OdbcConnection(connectionString)
)
{
connection.Open();
// Do work here.
}
Slide 13
Connecting to an Oracle Data Source
// Assumes connectionString is a valid connection string.
using (
OracleConnection connection =
new OracleConnection(connectionString)
)
{
connection.Open();
// Do work here.
}
Slide 14
Commands and Parameters
• After establishing a connection to a data source, you
can execute commands and return results from the
data source using a DbCommand object.
• Create a command for a particular connection using
the CreateCommand method of a DbConnection
object.
• The SQL statement being executed by the command
can be configured using the CommandText property
Slide 15
Executing a Command
• Each .NET Framework data provider has its own
command object that inherits from DbCommand
– Data Provider for OLE DB includes an OleDbCommand
object
– Data Provider for SQL Server includes a SqlCommand
object
– Data Provider for ODBC includes an OdbcCommand object
– Data Provider for Oracle includes an OracleCommand
object
Slide 16
Command Execution Methods & Command
Types
Command Objects expose methods for executing commands based on the type of command
and desired return value as described below:
Slide 17
ExecuteReader Example
public void ReadMyData(string connectionString)
{ //Executes commands that return rows.
string queryString = "SELECT OrderID, CustomerID FROM Orders";
using (
OleDbConnection connection = new OleDbConnection(connectionString)
)
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + ", " +
reader.GetString(1));
}
// always call Close when done reading.
reader.Close();
}
} Slide 18
ExecuteNonQuery Example
public void InsertRow(string connectionString, string insertSQL)
{
using (OdbcConnection connection =
new OdbcConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OdbcCommand command = new OdbcCommand(insertSQL, connection);
Slide 20
Using Parameters
• Command objects use parameters to pass values to
SQL statements or stored procedures, providing type
checking and validation
• Unlike command text, parameter input is treated as a
literal value, not as executable code.
– This behavior helps guard against "SQL injection" attack
• When adding parameters, you must supply a
ParameterDirection property for parameters other
than input parameters.
Slide 21
ParameterDirection
Slide 22
Parameter Placeholders and Data Types
• The syntax for parameter placeholders depends on the data
source.
• The SqlCommand data provider uses named parameters in the
format @parametername
• With an OleDbCommand or OdbcCommand, parameters must be
added to the Parameters collection in the order defined
• You specify the type of a Parameter in a generic manner by
setting the DbType property of the Parameter object to a
particular DbType.
• E.g. DbType:
– Boolean, Binary, DateTime, Date, Decimal, Double, Int16, Int32, Int64,
String, VarNumeric, UInt16, UInt32, UInt64
Slide 23
Parameter Placeholders
Slide 24
Adding Parameters
• Each .NET Framework data provider has its own
command object that inherits from DbParameter
– Data Provider for OLE DB includes an OleDbParameter
object
– Data Provider for SQL Server includes a SqlParameter
object
– Data Provider for ODBC includes an OdbcParameter object
– Data Provider for Oracle includes an OracleParameter
object
Slide 25
Parameter Example
sql = SELECT * FROM Customers WHERE CustomerID = ?
OdbcParameter parameter =
new OdbcParameter(“@p1”,OdbcType.Int);
parameter.Value = 20;
parameter.Direction = ParameterDirection.Input;
command.Add(parameter);
Slide 26
DataReaders
• You can use ADO.NET DataReader to retrieve a read-
only, forward-only stream of data from a database.
• Results are returned as the query executes
• Results are stored in the network buffer on the client
until they are requested using the Read method of
the DataReader.
• Using the DataReader can increase application
performance both by
– retrieving data as soon as it is available,
– and (by default) storing only one row at a time in memory
Slide 27
DbDataReaders
• Each .NET Framework data provider has its own
DbDataReaders
– Data Provider for OLE DB includes an OleDbDataReader
object
– Data Provider for SQL Server includes a SqlDataReader
object
– Data Provider for ODBC includes an OdbcDataReader
object
– Data Provider for Oracle includes an OracleDataReader
object
Slide 28
DbDataReader Example
static void HasRows(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
Slide 29
DataAdapters
• A DataAdapter is used to retrieve data from a data
source and populate tables within a DataSet.
• Each .NET Framework data provider has a
DbDataAdapter object
– Data Provider for OLE DB -> OleDbDataAdapter
– Data Provider for SQL Server -> SqlDataAdapter
– Data Provider for ODBC -> OdbcDataAdapter
– Data Provider for Oracle -> OracleDataAdapter
Slide 30
DataAdapter Example
using (connection)
{
// Define the query.
string queryString = "SELECT CategoryName FROM Categories";
adapter.SelectCommand = selectCMD;
foreach(
DataRow studentRow in studentDataSet.Tables[”students"].Rows
) {
Console.WriteLine($"ID: {studentRow["id"].ToString()}");
Console.WriteLine($"NAME: {studentRow["name"].ToString()}");
Console.WriteLine($"GENDER: {studentRow["gender"].ToString()}");
Console.WriteLine(
$"INDEX NUMBER: {studentRow["index_number"].ToString()}”
);
}
}
Slide 32
Combining Multiple DataAdapters
• Any number of DataAdapter objects can be used
with a DataSet
• DataRelation and Constraint objects can be added to
the DataSet locally, which enables you to relate data
from dissimilar data sources.
Slide 33
Populating a DataSet from Multiple
DataAdapters
SqlDataAdapter custAdapter = new SqlDataAdapter(
"SELECT * FROM dbo.Customers", customerConnection);
custAdapter.Fill(customerOrders, "Customers");
ordAdapter.Fill(customerOrders, "Orders");
Slide 34
Generating Commands with
CommandBuilders
• If your DataTable maps to a single database table,
you can use DbCommandBuilder to build
commands.
• DbCommandBuilder object can automatically
generate the DeleteCommand, InsertCommand, and
UpdateCommand of the DbDataAdapter.
– As a minimum requirement for automatic command
generation, set the SelectCommand property
– The SelectCommand must also return at least one primary
key or unique column
Slide 35
CommandBuilder Objects
• Each .NET Framework data provider has a
DbCommandBuilder object
– Data Provider for OLE DB -> OleDbCommandBuilder
– Data Provider for SQL Server -> SqlCommandBuilder
– Data Provider for ODBC -> OdbcCommandBuilder
– Data Provider for Oracle -> OracleCommandBuilder
Slide 36
Generating Commands with
DbCommandBuilder
OdbcDataAdapter adapter = new OdbcDataAdapter(
"SELECT * FROM dbo.Customers", connection
);
Console.WriteLine(builder.GetInsertCommand().CommandText);
Console.WriteLine(builder.GetDeleteCommand().CommandText);
Console.WriteLine(builder.GetUpdateCommand().CommandText);
Slide 37